考虑下面以串行/顺序方式读取文件数组的代码。readFiles返回一个承诺,只有在顺序读取所有文件后才会解析这个承诺。

var readFile = function(file) {
  ... // Returns a promise.
};

var readFiles = function(files) {
  return new Promise((resolve, reject) => {
    var readSequential = function(index) {
      if (index >= files.length) {
        resolve();
      } else {
        readFile(files[index]).then(function() {
          readSequential(index + 1);
        }).catch(reject);
      }
    };

    readSequential(0); // Start with the first file!
  });
};

上面的代码可以工作,但是我不喜欢为了使事情按顺序发生而进行递归。是否有一种更简单的方法可以重写这段代码,这样我就不必使用奇怪的readSequential函数了?

最初我尝试使用Promise。但是这会导致所有的readFile调用并发发生,这不是我想要的:

var readFiles = function(files) {
  return Promise.all(files.map(function(file) {
    return readFile(file);
  }));
};

当前回答

使用Array.prototype。Reduce,并记住将承诺包装在函数中,否则它们将已经在运行!

// array of Promise providers

const providers = [
  function(){
     return Promise.resolve(1);
  },
  function(){
     return Promise.resolve(2);
  },
  function(){
     return Promise.resolve(3);
  }
]


const inSeries = function(providers){

  const seed = Promise.resolve(null); 

  return providers.reduce(function(a,b){
      return a.then(b);
  }, seed);
};

很好很简单…… 您应该能够为性能等重新使用相同的种子。

在使用reduce时,防止空数组或只有一个元素的数组是很重要的,所以这个技术是你最好的选择:

   const providers = [
      function(v){
         return Promise.resolve(v+1);
      },
      function(v){
         return Promise.resolve(v+2);
      },
      function(v){
         return Promise.resolve(v+3);
      }
    ]

    const inSeries = function(providers, initialVal){

        if(providers.length < 1){
            return Promise.resolve(null)
        }

        return providers.reduce((a,b) => a.then(b), providers.shift()(initialVal));
    };

然后像这样叫它:

inSeries(providers, 1).then(v => {
   console.log(v);  // 7
});

其他回答

你可以使用这个函数来获取promiseFactories List:

function executeSequentially(promiseFactories) {
    var result = Promise.resolve();
    promiseFactories.forEach(function (promiseFactory) {
        result = result.then(promiseFactory);
    });
    return result;
}

Promise Factory是一个简单的函数,返回一个Promise:

function myPromiseFactory() {
    return somethingThatCreatesAPromise();
}

它之所以有效,是因为承诺工厂直到被要求才创建承诺。它的工作方式与then函数相同——事实上,它是一样的!

你根本不想在一组承诺上操作。根据Promise规范,一旦创建了Promise,它就开始执行。所以你真正想要的是一系列的承诺工厂…

如果你想了解更多的承诺,你应该检查这个链接: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html

这个问题很老了,但我们生活在ES6和函数式JavaScript的世界里,所以让我们看看如何改进。

因为承诺会立即执行,所以我们不能只创建一个承诺数组,它们会同时发射。

相反,我们需要创建一个返回承诺的函数数组。然后依次执行每个函数,然后在其中启动promise。

我们可以用几种方法来解决这个问题,但我最喜欢的方法是reduce。

把“减少”和“承诺”结合起来使用有点棘手,所以我把这句话分成了几个易于理解的小部分。

这个函数的本质是使用以promise .resolve([])或包含空数组的promise开头的reduce。

然后,这个承诺将作为承诺传递给reduce方法。这是将每个承诺按顺序连接在一起的关键。要执行的下一个promise是func,当then触发时,结果被连接起来,然后返回该promise,使用下一个promise函数执行reduce循环。

一旦执行了所有的promise,返回的promise将包含每个promise的所有结果的数组。

ES6示例(一行)

/*
 * serial executes Promises sequentially.
 * @param {funcs} An array of funcs that return promises.
 * @example
 * const urls = ['/url1', '/url2', '/url3']
 * serial(urls.map(url => () => $.ajax(url)))
 *     .then(console.log.bind(console))
 */
const serial = funcs =>
    funcs.reduce((promise, func) =>
        promise.then(result => func().then(Array.prototype.concat.bind(result))), Promise.resolve([]))

ES6示例(分解)

// broken down to for easier understanding

const concat = list => Array.prototype.concat.bind(list)
const promiseConcat = f => x => f().then(concat(x))
const promiseReduce = (acc, x) => acc.then(promiseConcat(x))
/*
 * serial executes Promises sequentially.
 * @param {funcs} An array of funcs that return promises.
 * @example
 * const urls = ['/url1', '/url2', '/url3']
 * serial(urls.map(url => () => $.ajax(url)))
 *     .then(console.log.bind(console))
 */
const serial = funcs => funcs.reduce(promiseReduce, Promise.resolve([]))

用法:

// first take your work
const urls = ['/url1', '/url2', '/url3', '/url4']

// next convert each item to a function that returns a promise
const funcs = urls.map(url => () => $.ajax(url))

// execute them serially
serial(funcs)
    .then(console.log.bind(console))

我喜欢的解决方案:

function processArray(arr, fn) {
    return arr.reduce(
        (p, v) => p.then((a) => fn(v).then(r => a.concat([r]))),
        Promise.resolve([])
    );
}

它与这里发表的其他文章没有本质区别,但是:

将函数应用于序列中的项 解析为结果数组 不需要async/await(支持仍然非常有限,大约在2017年) 使用箭头函数;非常简洁

使用示例:

const numbers = [0, 4, 20, 100];
const multiplyBy3 = (x) => new Promise(res => res(x * 3));

// Prints [ 0, 12, 60, 300 ]
processArray(numbers, multiplyBy3).then(console.log);

在当前合理的Chrome (v59)和NodeJS (v8.1.2)上测试。

数组push和pop方法可用于承诺序列。当你需要额外的数据时,你也可以推出新的承诺。这是代码,我将使用在React无限加载器加载页面序列。

var promises = [Promise.resolve()]; 函数methodThatReturnsAPromise(page) { 返回新的承诺((resolve, reject) => { setTimeout(() => { console.log(“解决- ${页面}!${new Date()} '); 解决(); }, 1000); }); } 函数pushPromise(page) { promises.push (promises.pop()。然后(function () { 返回methodThatReturnsAPromise(页面) })); } pushPromise (1); pushPromise (2); pushPromise (3);

nodejs中有承诺序列。

const promiseSequence = require('promise-sequence');
return promiseSequence(arr.map(el => () => doPromise(el)));