按照這個示例如何擺脫循環中的一系列異步操作?
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