如何回报所有的诺言

我在这个脚本中有4个阶段,我正在做,可以叫第一阶段,第二阶段第三阶段和第四阶段。 在每个阶段,我提供了一个文件数组,我使用map函数遍历每个文件,做一些东西,并返回我所需要的,如下所示:

phaseOne:

files = files.map((file) => { // do some stuff, and return. }); 

而且我正在使用reduce来调用每个阶段:

 [ 'phaseOne', 'phaseTwo', 'phaseThree', 'phaseFour' ].reduce... call one, after call two, after call three. 

问题开始时,我在第二阶段的asynchronous操作:

phaseOne:

 files = files.map((file) => { return new Promise((resolve) => { //async, if ok resolve. }); }); 

所以,当第三阶段被调用时,我需要使用Promise.all来等待数组中的每个项目:

phaseThree:

 Promise.all(files).then((files) => { files = files.map((file) => { // sync operation. }); return files; // is this right? }); 

现在真正的问题是:如何在第四阶段访问文件? 这些文件只是一个Promise { <pending> } ,并且是空的。

谢谢。

基于你在这里做什么,我有点困惑。 有一件事我想澄清的是, Promise.all()对于并行运行依赖关系非常Promise.all() 。 在Promise.all()运行一个单一的承诺完全失败的目的。

如果我正确地理解了你,你应该看起来像这样(伪代码):

 Promise.all([phaseOnePromise, phaseTwoPromise]) .then(function(results) { // Results are returned in the order that they're passed into Promise.all() var phaseOneResults = results[0]; var phaseTwoResults = results[1]; return phaseThreePromise(phaseOneResults, phaseTwoResults); }) .then(function(finalResult) { // You're done! }); 

您还可以devisephaseThreePromise来接受单个数组参数,并像这样简化它:

 Promise.all([phaseOnePromise, phaseTwoPromise]) .then(phaseThreePromise) .then(function(finalResult) { // You're done! }); 

不同的名字不重要,但可以帮助清晰。 你真正的问题是你没有使用最终的数据

 Promise.all(files).then((files1) => { return files1.map((file) => { // sync operation. }); }) .then(files2 => { // use the data });