Javascript 我需要从异步代码返回一个值,但我只得到处于{pending}状态的Promise对象

Javascript 我需要从异步代码返回一个值,但我只得到处于{pending}状态的Promise对象,javascript,node.js,async-await,es6-promise,Javascript,Node.js,Async Await,Es6 Promise,拜托,我知道这个问题以前已经回答过了。我读过&,但我还不知道如何修复我的代码 我创建了一个函数来读取一些文件的内容&返回anewpromise。这是函数: // 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' ]; /

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

我创建了一个
函数
来读取一些文件的内容&
返回
a
newpromise
。这是
函数

// 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);
    });
  });
};
现在,我正在尝试循环通过一个
数组
来存储每个文件的
路径
,调用
readFileContent()
方法并使用
map()将当前循环的值作为其
参数传递
方法,因为我想用每个文件的内容创建另一个
数组
,其中包含
字符串

这就是我尝试过的:

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

我做错了什么?

您想要的是使用
Promise.all(allSpecFilesArr)
,因为这是一个承诺数组。您可以等待它,您将收到一个从内部数据库返回的数据数组

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)
})()

第二种解决方案部分正确。您正在等待map函数的结果,在本例中,map函数是一个承诺数组

const fileContents = await Promise.all(allSpecFilesArr);
如果您在map调用前删除wait并调用
wait Promise.all(allSpecFilesArr)
您将获得所需的内容

你可以这样做:

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

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

使用Promise.all(allSpecFilesArr)必须调用
Promise.all(allSpecFilesArr)。然后(…)
这是不正确的,您可以将一个异步函数传递给
map
,您只需期望将得到一个Promise数组。您可以使用类似于
Promise.all([1,2,3].map(async(x)=>x)).then(console.log)
的东西轻松地测试这一点。另外,在一系列承诺中没有
all
方法,我想你指的是
Promise.all
@ZacAnger,谢谢你指出错误,我编辑了它。对于map部分,您完全正确,我的意思是没有承诺。我们不能将异步函数与map这样的函数一起使用,因为同步代码不会坐在那里等待异步代码解析,相反,它会启动函数并继续。为了避免混淆,我将删除这一段。有关使用带承诺的地图的详细信息