如何按顺序在 Q 中链接可变数量的承诺? [英] How to chain a variable number of promises in Q, in order?

查看:24
本文介绍了如何按顺序在 Q 中链接可变数量的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到 在 Q 中链接任意数量的承诺;我的问题是不同的.

I have seen Chaining an arbitrary number of promises in Q ; my question is different.

如何进行可变数量的调用,每个调用都按顺序异步返回?
该场景是一组 HTTP 请求,其数量和类型由第一个 HTTP 请求的结果决定.

How can I make a variable number of calls, each of which returns asynchronously, in order?
The scenario is a set of HTTP requests, the number and type of which is determined by the results of the first HTTP request.

我想简单地做到这一点.

I'd like to do this simply.

我也看到了这个答案,它暗示了这样的事情:

I have also seen this answer which suggests something like this:

var q = require('q'),
    itemsToProcess =  ["one", "two", "three", "four", "five"];

function getDeferredResult(prevResult) {
  return (function (someResult) {
    var deferred = q.defer();
    // any async function (setTimeout for now will do, $.ajax() later)
    setTimeout(function () {
      var nextResult = (someResult || "Initial_Blank_Value ") + ".." + itemsToProcess[0];
      itemsToProcess = itemsToProcess.splice(1);
      console.log("tick", nextResult, "Array:", itemsToProcess);
      deferred.resolve(nextResult);
    }, 600);

    return deferred.promise;
  }(prevResult));
}

var chain = q.resolve("start");
for (var i = itemsToProcess.length; i > 0; i--) {
    chain = chain.then(getDeferredResult);
}

...但以这种方式循环遍历 itemsToProcess 似乎很尴尬.或者定义一个称为循环"的新函数来抽象递归.什么是更好的方法?

...but it seems awkward to loop through the itemsToProcess in that way. Or to define a new function called "loop" that abstracts the recursion. What's a better way?

推荐答案

[].reduce.

var chain = itemsToProcess.reduce(function (previous, item) {
    return previous.then(function (previousValue) {
        // do what you want with previous value
        // return your async operation
        return Q.delay(100);
    })
}, Q.resolve(/* set the first "previousValue" here */));

chain.then(function (lastResult) {
    // ...
});

reduce 遍历数组,传入上一次迭代的返回值.在这种情况下,您将返回承诺,因此每次链接 then 时.您提供了一个初始承诺(就像您对 q.resolve("start") 所做的那样)以开始工作.

reduce iterates through the array, passing in the returned value of the previous iteration. In this case you're returning promises, and so each time you are chaining a then. You provide an initial promise (as you did with q.resolve("start")) to kick things off.

一开始可能需要一段时间才能理解这里发生的事情,但如果你花一点时间来理解它,那么这是一个可以在任何地方使用的简单模式,无需设置任何机器.

At first it can take a while to wrap your head around what's going on here but if you take a moment to work through it then it's an easy pattern to use anywhere, without having to set up any machinery.

这篇关于如何按顺序在 Q 中链接可变数量的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆