我试图动态链接承诺,以处理需要按顺序发生的未知数量的异步调用。我使用支持Promise的IO.JS/chrome。javascript ES6动态链接承诺
承诺的创建立即触发(至少相对于控制台输出)。我期待能够收集承诺,然后传递给Promise.all,但那时他们已经因为我不明白的原因而被解雇了。
这里有那么链接的一种方法,通过一个评论对Dynamic Chaining in Javascript Promises
var lastPr = null;
console.log(" exit setup......................");
while(this.statesToExit.length > 0) {
var v = this.statesToExit.shift();
console.log("new Promise...");
var pr = new Promise(function (resolve, reject) {
console.log("doing Exit stuff at time " +curTime);
resolve(); //SOMETHING MORE SUBSTANTIAL GOES HERE
});
console.log("lastPr.then.");
if (lastPr != null) {
lastPr.then(pr);
}
lastPr = pr;
// console.log("adding pr to worklist");
// promiseList.push(pr);
// });
}
提出的另一种方法是
var promiseList= [];
console.log(" exit setup......................");
while(this.statesToExit.length > 0) {
var v = this.statesToExit.shift();
console.log("new Promise...");
var pr = new Promise(function (resolve, reject) {
console.log("doing Exit stuff at time " +curTime);
resolve(); //SOMETHING MORE SUBSTANTIAL GOES HERE
});
console.log("adding pr to worklist");
promiseList.push(pr);
});
}
console.log("Transition *START*-" +promiseList.length +" ");
Promise.all(promiseList).catch(function(error) {
console.log("Part of TransitionCursor Failed!", error);
}).then(this.summarizeWorkDone());
在这两种情况下,输出类似
new Promise...
doing Exit stuff at time 0
new Promise...
doing Exit stuff at time 0
"Transition *START*-"
VS预计的
new Promise...
new Promise...
"Transition *START*-"
doing Exit stuff at time 0
doing Exit stuff at time 0
我该如何动态创建一个承诺列表以便稍后执行?
它为什么无论什么时候到底是执行承诺的身体吗?承诺不保证他们的身体稍后会被执行。 – zerkms
也许承诺不是你在这里需要的东西,看起来像执行顺序很重要,所以你想建立某种按摩队列,然后让它执行..但在你的例子中,如果只有一个项目statesToExit ? – webdeb
你对承诺做什么以及如何使用它们的理解看起来相当遥远。我们可以帮助您重新构建,但需要了解是否希望所有异步操作以串行(一个接一个)或并行(全部同时开始)运行?我们还需要查看您的实际异步操作。现在你的问题中的代码完全是同步的,因此不需要承诺。 – jfriend00