考虑下面以串行/顺序方式读取文件数组的代码。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);
  }));
};

当前回答

数组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);

其他回答

正如Bergi所注意到的,我认为最好的和明确的解决方案是使用蓝鸟。每个,代码如下:

const BlueBird = require('bluebird');
BlueBird.each(files, fs.readFileAsync);

有一个npm包Promise Serial可以很好地做到这一点:

const Promise_serial = require('promise-serial');

 const promises =
    Array(15).fill()
    .map((_, i) =>
        () => new Promise(resolve => {
            console.log('promise '+i+' start');
            setTimeout(
                () => {
                    console.log('promise '+i+' end');
                    resolve('output-'+i);
                },
                500
            );
        })
    );


console.log('### Run promises in sequence')

Promise_serial(promises)

输出:

promise 0 start
promise 0 end
promise 1 start
promise 1 end
promise 2 start
promise 2 end
promise 3 start
promise 3 end
promise 4 start
promise 4 end
promise 5 start
promise 5 end
promise 6 start
promise 6 end
promise 7 start
promise 7 end

... etc

您还可以批处理或并行化它们。

参见:https://www.npmjs.com/package/promise-serial

这是我在各种项目中使用的顺序实现:

const file = [file1, file2, file3];
const fileContents = sequentially(readFile, files);

// somewhere else in the code:

export const sequentially = async <T, P>(
  toPromise: (element: T) => Promise<P>,
  elements: T[]
): Promise<P[]> => {
  const results: P[] = [];
  await elements.reduce(async (sequence, element) => {
    await sequence;
    results.push(await toPromise(element));
  }, Promise.resolve());

  return results;
};

我真的很喜欢@joelnet的回答,但对我来说,这种编码风格有点难以消化,所以我花了几天时间试图弄清楚如何以更可读的方式表达相同的解决方案,这就是我的想法,只是使用了不同的语法和一些注释。

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

// next convert each item to a function that returns a promise
const functions = urls.map((url) => {
  // For every url we return a new function
  return () => {
    return new Promise((resolve) => {
      // random wait in milliseconds
      const randomWait = parseInt((Math.random() * 1000),10)
      console.log('waiting to resolve in ms', randomWait)
      setTimeout(()=>resolve({randomWait, url}),randomWait)
    })
  }
})


const promiseReduce = (acc, next) => {
  // we wait for the accumulator to resolve it's promise
  return acc.then((accResult) => {
    // and then we return a new promise that will become
    // the new value for the accumulator
    return next().then((nextResult) => {
      // that eventually will resolve to a new array containing
      // the value of the two promises
      return accResult.concat(nextResult)
    })
  })
};
// the accumulator will always be a promise that resolves to an array
const accumulator = Promise.resolve([])

// we call reduce with the reduce function and the accumulator initial value
functions.reduce(promiseReduce, accumulator)
  .then((result) => {
    // let's display the final value here
    console.log('=== The final result ===')
    console.log(result)
  })

这里有很多答案,但我没有看到这个简单的解决方案:

await array.reduce(
  async (promise, member) => await myLongSequentialPromise(member),
  array[0]
)

证明:https://jsbin.com/nulafus/1/edit?js,控制台