如何简化Q promise示例

How to simplify Q promise example

本文关键字:示例 promise 何简化      更新时间:2023-09-26

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

我当然不想去回拨地狱,因此研究了Promises/A+规范示例和Q库。

我已经准备了一个异步函数,它应该会得到我想要的结果。但我想了解如何简化Sequential 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:  [] 
    */
    

提前感谢大家!

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

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();
});

jQueryAJAX还返回一个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();
    });
}