Node.js 如何按顺序运行此代码并在node js中获得结果
这个结果总是空的,因为它甚至在异步调用完成之前就返回了Node.js 如何按顺序运行此代码并在node js中获得结果,node.js,asynchronous,sequential,Node.js,Asynchronous,Sequential,这个结果总是空的,因为它甚至在异步调用完成之前就返回了 函数(myList){ 让结果=[] myList.forEach(异步函数(元素)){ //api调用 结果。推送(状态) } 返回结果 } 您不能将异步等待与forEach循环一起使用。将map与Promise一起使用。所有或都用于支持Promise的循环。例如: const myList = ['abc', 'def']; for (const foo of myList) { const result = await so
函数(myList){
让结果=[]
myList.forEach(异步函数(元素)){
//api调用
结果。推送(状态)
}
返回结果
}
您不能将异步等待与forEach循环一起使用。将map
与Promise一起使用。所有或都用于支持Promise的循环。例如:
const myList = ['abc', 'def'];
for (const foo of myList) {
const result = await someResultfromApi;
result.push(element);
}
return result;
数组方法不接受异步函数,因此,在这种特殊情况下,应该使用基本循环
function (myList) {
let result = [];
for (let element: myList) {
//api call with the await
result.push(status);
}
return result;
}
或者您可以使用reduce,如果您想使用数组本机函数,它将如下所示
function (myList) {
return myList.reduce(
(prev, element) => {
return prev.then(result => {
return http.get(/*some thing with the element*/).then(res => {
result.push(res);
return result;
})
});
},
Pormise.resolve([]));
}