【问题标题】:JavaScript async/await function not working properly [duplicate]JavaScript异步/等待功能无法正常工作[重复]
【发布时间】:2020-01-01 22:35:29
【问题描述】:
  • 第一部分

所以我有以下代码 =>

let array = [];

await objElements.forEach( async(element) => {
  let results = await axios.get('backend_route', {params: element});
  results.data.forEach(result => {
    array.push(result);

    console.log(result);
    console.log(array);
//  here the `result` variable is printed with the desired value and the array shows all the `result` singles values on it
  });
});

console.log(array);
// But here, like if I would like to return the array at the end, it is empty :(

这是关于 JavaScript ES6 顺便说一句,如果您有任何可能的解决方案,任何帮助表示赞赏,谢谢!

  • 第二部分

感谢您回答上一个问题,我一直在阅读 Promises,但仍然无法弄清楚我遇到的新问题,所以代码如下 =>

const promise = array.map(async(item) => {
  // here for each `item` I'm doing a call to the backend.
  let response = await axios.get('route_to_backend', {params: item});
  console.log(response);

  /*When I try to get the response from the backend, it always send me
  the response for the last `item` of the array, example: if the
  array is [12, 67, 95, 06], it will make the request to the backend 4
  times (length of the array) and always with the last item of the
  array (in this example `06`) :(*/
});

//Finally as per the example I was provided
await Promise.all(promise);

非常感谢您的回答(Y)

【问题讨论】:

  • 你可以发布一个可执行的sn-p来代替How to create a Minimal, Reproducible Example
  • 你是 console.logging array 同步但不等待你从你的异步函数得到的结果
  • 你需要使用一个承诺
  • 异步函数 f() { let array = []; for(let i=0; i { array.push(result); console.log(result); console.log(array); // 这里result 变量打印了所需的值,数组显示了所有result 单打值 }); } 控制台日志(数组); } 你可以这样使用。
  • 您也可以为此使用forof循环。let array = []; for(let element of objElements){ let results = await axios.get('backend_route', {params: element}); for(let result of results.data) { array.push(result); console.log(result); console.log(array); } } console.log(array);

标签: javascript ecmascript-6 async-await axios


【解决方案1】:

await objElements.forEach( async(element) => { 实际上不会等待内部异步函数。

你真正想做的更像是:

const promises = objElements.map(async (element) => {...});
const results = await Promise.all(promises);

这会创建一个带有.map 的promise 列表,然后等待Promise.all 加入它们。

results 应该是一个数组,其中包含任何解决的承诺,即无论您的内部异步函数返回什么

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2019-11-03
    相关资源
    最近更新 更多