不确定这是否是您需要的。但是我确实必须解决几种异步对话框的情况,所以这应该可以。请注意,这需要支持 Promise 的浏览器或要求您拥有 Promise shim。
var items = [1,2,3,4,5];
var chainObj = {}; // Set this up if you need to communicate info to subsequent items. Or you need some form of "reduce" capability.
var promise = Promise.resolve(accumObj); // The initial promise.
for (var i = 0; i < items.length; i++){
var currItem = items[i];
promise = promise.then(function(accumObj){
if (/*Need Async Stuffs*/){
return new Promise(function(resolve, reject){
/*perform some async stuff for the currItem. Once they're done, update accumObj and invoke the below function*/
resolve(accumObj);
});
} else {
/* Perform non-async stuffs for currItem, update accumObj as needed. */
return accumObj; // Return the accumObj for the next step.
}
});
}
promise.then(/*Put call back to finish up anything else that's left*/);
上面将保证每个“item”在前一个item完成之前不会开始处理,只要您在所有异步操作完成后才调用“resolve”(如果需要,在每个循环中将多个promise链接在一起)根据需要)。
简而言之,上面的调用创建了一个长长的 Promise 链,如下面的伪代码:
Promise.resolve(chainObj)
.then(/*Process items[0]*/)
.then(/*Process items[1]*/)
.then(/*Process items[2]*/)
.then(/*Process items[3]*/)
.then(/*Process items[4]*/)
.then(/*Process for when everything is done*/)
每个流程步骤要么立即解析(else 部分,也称为非异步路径),要么在一些异步操作后解析(/*Need Async stuffs*/ 路径)。并且只有在前一个流程步骤解决后,后续流程步骤才会开始。 accumObj 允许您累积每一步的结果并将其传递给下一个。
代码块中的最后一个promise.then 是处理完所有内容后您可以执行任何最终操作的地方。
CAVEAT:上面的示例代码不处理任何错误/异常。
编辑#1:
要处理比较复杂的操作,请将promise = promise.then... 块修改为此。
promise = promise.then(function(accumObj){
// Start running you async stuffs
var promises = [];
promises.push(new Promise(function(resolve, reject){
// Async function #1. Invoke resolve when the async function completes (simplest solution, pass "resolve" to whatever callback the
// The async fucntion uses.
});
promises.push(new Promise(function(resolve, reject){ // Async function #2. });
promises.push(new Promise(function(resolve, reject){ // Async function #3. });
// ...
promises.push(new Promise(function(resolve, reject){ // Async function #Last. });
// Do synchronous function here.
return Promise.All(promises).then(function(results){
// Process the results from your async calls, udpate accumObj as needed.
return accumObj;
});
});
上面所做的是在处理同步函数之前为当前项目启动所有异步函数(让异步并行运行)。 return Promise.All(promises).then(function(results){return accumObj;}); 返回另一个执行以下操作的承诺。
- “等待”(以异步方式发生)直到
promises 中的每个承诺都得到解决。
- 在
then 回调中调用函数,并使用来自每个承诺的已解析值数组(results[0] 是已解析值或 promises[0],依此类推)。
- 函数返回
accumObj,成为return Promise.All(promises).then(function(results){return accumObj;});的解析值。