我正在开发一个简单的应用程序,它可以进行顺序 ajax 调用,将第一次调用的结果传递给下一次调用。
当然,我不想进入回调地狱,因此查看Promises/A+规范示例和Q 库。
我准备了一个异步函数,它应该会产生我想要的结果。但我想了解如何简化顺序承诺传递。
现在我仍在阅读如何最好地使用承诺和延迟对象,所以请原谅我非常幼稚的代码。
所以现在我在看两件事:
- 简化 Promise 顺序的方法(在我的情况下相互依赖)
建议
var modifyableObject = { toProcess : ["one", "two", "three", "four", "five"] } function returnsDeferredResults(someResult) { var deferred = Q.defer(); // my async function (setTimeout for now will do, $.ajax() later) setTimeout(function () { var nextResult = (someResult || " Initial_Blank_Value ") + "..." + modifyableObject.toProcess[0]; modifyableObject.toProcess = modifyableObject.toProcess.splice(1); console.log("New Tick Result: ", nextResult, "Array: ", modifyableObject.toProcess); deferred.resolve( nextResult); }, 200); return deferred.promise; } //$("#test_promise").click(function () { function getDeferredResult(prevResult) { return returnsDeferredResults(prevResult); } var prevResult = getDeferredResult(); var nextTick = ""; for (var i = modifyableObject.toProcess.length; i > 1; i --) { if (nextTick) nextTick = nextTick.then(getDeferredResult); else nextTick = prevResult.then(getDeferredResult); } //nextTick.fin(function(){ ...}); //}); /* New Tick Result: Initial_Blank_Value ...one Array: ["two", "three", "four", "five"] New Tick Result: Initial_Blank_Value ...one...two Array: ["three", "four", "five"] New Tick Result: Initial_Blank_Value ...one...two...three Array: ["four", "five"] New Tick Result: Initial_Blank_Value ...one...two...three...four Array: ["five"] New Tick Result: Initial_Blank_Value ...one...two...three...four...five Array: [] */
提前谢谢大家!