1

我正在开发一个简单的应用程序,它可以进行顺序 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:  [] 
    */
    

提前谢谢大家!

4

1 回答 1

5

您可以通过组合两个变量来简化循环:

var nextTick = getDeferredResult();

for (var i = modifyableObject.toProcess.length; i > 1; i --) {
    nextTick = nextTick.then(getDeferredResult);
}

或者,

return modifyableObject.toProcess.reduce(function(promise, item) {
    return promise.then(getDeferredResult);
}, Q.resolve());

您也可以简化您的功能:

return Q.delay(200).then(function) { 
    return "..." + modifyableObject.toProcess.shift();
});

jQuery AJAX 还返回一个 Promise,它与 Q 兼容(在最新版本的 jQuery 中)

然后,您可以通过将每个项目传递给函数来组合这两个改进:

return modifyableObject.toProcess.reduce(function(promise, item) {
    return promise.then(processItem.bind(null, item));
}, Q.resolve());

function processItem(item) {
    return Q.delay(200).then(function) { 
        return "..." + modifyableObject.toProcess.shift();
    });
}
于 2013-07-03T15:51:36.237 回答