【发布时间】: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