如何简化Q promise示例

时间:2013-07-03 15:46:18

标签: javascript promise deferred q

我正在研究一个简单的应用程序,它使顺序 ajax调用,将第一次调用的结果传递给下一个调用。

当然,我不想进入回调地狱, 因此,请查看Promises/A+规范示例和Q library

我准备了一个异步函数,它应该导致我想要的东西。 但我希望能够深入了解如何简化顺序承诺传递。

目前我还在阅读如何最好地使用promises和deferred对象,所以请原谅 我是非常天真的代码。

所以现在我正在研究两件事:

  • 简化承诺排序的方式(取决于一个 另一个在我的情况下)
  • 建议

    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:  [] 
    */
    

提前谢谢大家!

1 个答案:

答案 0 :(得分: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也返回一个承诺,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();
    });
}