bao*_*uss 1 javascript return promise
我确实意识到,当在.then()处理程序中返回非承诺时,它会立即传递到下一个处理程序,如果返回了一个promise,则在执行promise传递给它之前,将暂停执行该promise以进行解决。下一个处理程序。
我也知道,一个承诺只能返回一个值。
那只蜜蜂说,我将如何从一个.then()处理函数返回多个参数到下一个?Esepcailly,如果它是承诺和非承诺的混合。目前,我将所有内容放入自定义对象中,将其返回,并在随后的then()处理函数中使用async await来解决承诺。
然后是使用已解决的承诺值和非承诺值一起进行一些工作。
这很好用,但是我的直觉说这不是应该的方式……也许?
例:
const current = 'blah';
const previous = 'blubb';
this.doSomeAsyncWork()
.then(
result => {
const nonPromiseValue = new domSomethingSynchronous(current, previous);
// "custom object, mix of promises and non-promises"
return {
nonPromise: nonPromise,
promiseA: ControllerA.asyncOperationA(current, nonPromiseValue.someProperty),
promiseB: ControllerB.asyncOperationB(nonPromiseValue.someOtherProperty),
}
}
)
.then(
async x => {
const nonPromiseValue = x.nonPromiseValue;
const valueA = await x.promiseA;
const valueB = await x.promiseB;
// do something with the results of those three variables
}
)
.catch(
// ...
)
Run Code Online (Sandbox Code Playgroud)
return Promise.all
在a的末尾对Promises和non-Promises数组使用.then
,然后可以在下一个中立即解构结果.then
,不需要await
也不async
需要。
在Promise.all
将解决,一旦所有Promises
的数组中已经解决。传递给它的非Promise只会传递给next .then
。
const makeProm = () => new Promise(resolve => setTimeout(resolve, 1000, 'resolveValue'));
Promise.resolve()
.then(() => {
const prom = makeProm();
const otherValue = 'foo';
return Promise.all([prom, otherValue]);
})
.then(([resolveValue, otherValue]) => {
console.log(resolveValue, otherValue);
});
Run Code Online (Sandbox Code Playgroud)