按照这个示例如何摆脱循环中的一系列异步操作?
Dojo FAQ: How can I sequence asynchronous operations?
function doNext(previousValue) {
var dfd = new Deferred();
// perform some async logic; resolve the promise
setTimeout(function() {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
dfd.resolve(previousValue + next);
}, 50);
return dfd.promise;
}
var promise = doNext('a');
for (var i = 0; i < 9; i++) {
promise = promise.then(doNext);
}
promise.then(function (finalResult) {
// 'doNext' will have been invoked 10 times, each
// invocation only occurring after the previous one completed
// 'finalResult' will be the value returned
// by the last invocation of 'doNext': 'abcdefghijk'
console.log(finalResult);
});
如何打破循环 - 即停止处理时doNext符合一定条件的后续doNext函数调用 - 例如停车时,下一个字符是“d '并将计算值返回到该点?
编辑:到目前为止我尝试使用deferred cancel()方法,但它只是杀死进程,并且什么都不返回。
setTimeout(function() {
var next = String.fromCharCode(previousValue.charCodeAt(previousValue.length - 1) + 1);
if(previousValue + next == 'abc')
dfd.cancel('abc');
else
dfd.resolve(previousValue + next);
}, 50);
我是想你的榜样,但两个问题1) - 什么是“何时”? 2)单步执行代码,它从不将最终结果写入控制台,是否应该这样做? – erotavlas
['when when](https://dojotoolkit.org/reference-guide/1.10/dojo/when.html)似乎是dojo写作方式['Promise.resolve'](https://developer.mozilla .ORG/EN-US /文档/网络/的JavaScript /参考/ Global_Objects /无极/解析)。关于最终结果,是的,它绝对应该,尽管我没有测试过代码(并且只是注意到我忘记了通过'i')。 – Bergi