我需要 return 来自异步代码的值,但我只是得到了处于 { pending } 状态的 Promise 对象

I need to return a value from a asynchronous code, but I just get the Promise object in { pending } status

拜托,我知道这个问题之前已经回答过了。我已阅读 & this article,但我还不知道如何修复我的代码。

我创建了一个 function 来读取一些文件的内容 & returns 一个 new Promise。这是 function:

// array of string representing each file's path
const allSpecFiles = [
  '/path/to/the/file1.spec.js',
  '/path/to/the/file2.spec.js',
  '/path/to/the/file3.spec.js'
];

// method to read an individual file content & return a Promise
const readFileContent = file => {
  return new Promise((resolve, reject) => {
    fs.readFile(file, 'utf8', (err, data) => {
      if (err) return reject(err);
      return resolve(data);
    });
  });
};

现在,我正在尝试循环存储每个文件的 patharray of strings,调用 readFileContent() 方法并将当前循环的值作为其传递param 使用 map() 方法,因为我想用每个文件的内容创建另一个 array of strings

这是我试过的:

const allSpecFilesArr = allSpecFiles.map(async file => await readFileContent(file));
console.log(allSpecFilesArr); // I get Promise { <pending> }

我也试过像这样包装整个 script

(async () => {
  const allSpecFilesArr = await allSpecFiles.map(file => readFileContent(file));
  console.log(allSpecFilesArr); // still prints Promise { <pending> }
})();

我做错了什么?

你想要的是使用 Promise.all(allSpecFilesArr) 因为那是一个承诺数组。您可以 await 它,您将收到一组从内部 resolved promise 返回的数据。

const fileContents = await Promise.all(allSpecFilesArr);

不需要换行fs.readFile,使用fs/promises。试试这个:

const fs = require('fs/promises')
const paths = [ './one', './two' ]
;(async () => {
  const contents = await Promise.all(paths.map((p) => fs.readFile(p, 'utf8')))
  console.log(contents)
})()

第二种解法部分正确。你是 awaiting map 函数的结果,在本例中,它是一个 promises 数组。

如果您删除了 map 调用前的 await 并调用了 await Promise.all(allSpecFilesArr),您将得到所需的。

你可以这样做:

async read (paths) {
 const promises = [];
 for (path in paths) {
   promises.push(readFileContent(path));
 }

 
 const arrOfContentYouWant = await Promise.all(promises);
 return arrOfContentYouWant;
}