【发布时间】:2013-07-01 09:45:54
【问题描述】:
我正在开发一个简单的应用程序,它使顺序 ajax 调用,将第一次调用的结果传递给下一次调用。
我当然不想进入回调地狱, 因此请查看Promises/A+ 规范示例和Q library。
我已经准备了一个异步函数,它应该会产生我想要的结果。 但我想了解如何简化顺序承诺传递。
目前我仍在阅读如何最好地使用承诺和延迟对象,请原谅 我的代码非常幼稚。
所以现在我在看两件事:
- 简化 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: [] */
提前谢谢大家!
【问题讨论】:
-
我真的不明白你为什么在这里使用承诺。他们的观点应该是不再需要像
modifyableObject这样的全局变量。 -
这只是一个简化并放入“全局”范围的原型代码。我将使用
$.ajax()而不是setTimeout函数,modifyableObject将替换为我需要传递给$.ajax()调用的数据。
标签: javascript promise deferred q