Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何按顺序运行此代码并在node js中获得结果_Node.js_Asynchronous_Sequential - Fatal编程技术网

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([]));
}