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' ]; /
函数
来读取一些文件的内容&返回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'
];
// 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这样的函数一起使用,因为同步代码不会坐在那里等待异步代码解析,相反,它会启动函数并继续。为了避免混淆,我将删除这一段。有关使用带承诺的地图的详细信息