This question already has answers here:
Calling functions with setTimeout()
                                
                                    (6个答案)
                                
                        
                                3年前关闭。
            
                    
我试图理解ES6的承诺,在那里,我以为自己拥有了它,但我想不是。

因此,我想创建/读取一堆文件,并且仅在此操作完成之后,继续执行下一个操作。对我来说,这很适合Promises,但是对于为什么我的第二个操作在我的第一个操作完成之前返回的原因,我感到困惑。

我创建了一个返回承诺的函数ensureFileExists,并将其作为回调传递给fileNames.map。这会将true数组记录到控制台,这是我期望的。但是我的困惑是,我认为借调的then仅在我的第一个then完成后才能被调用。

如果有人能详细说明为什么我的第二个then在我的第一个then之前返回,我将不胜感激。

getFileNames(ensureFileExists) {
  for(let i = 0; i < this.fileCount; i++) {
    this.fileNames.push(this.generateRandomfileNames());
  };
  Promise.all(this.fileNames.map((file) => ensureFileExists(file)))
         .then(values => console.log(values))
         .then(console.log(1)) // Why is this logged before values???
         .catch(err => console.log(err))
};

ensureFileExists(file) {
  return new Promise((resolve, reject) => {
    let filePath = path.join(this.src, file);

    fsExtra.ensureFile(filePath, (err) => {
      if (err === 'undefined') {
        reject(new Error('Error creating file'));
      } else {
        resolve(true);
      }
    });
  })
};

最佳答案

这行:

.then(console.log(1))


立即调用console.log,并将返回值传递给then方法。

您可能希望更像上一行中的回调函数,如下所示:

.then(() => console.log(1))

10-05 20:40
查看更多