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

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

问题描述

我已经看到在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 进行迭代通过数组,传入上一次迭代的返回值.在这种情况下,您将返回承诺,因此每次您链接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中链接可变数量的Promise?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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