【发布时间】:2018-05-18 02:24:41
【问题描述】:
我正在尝试使用 Axios 和 Node.js 向网络服务器发出一些 GET 请求。我使用异步函数获取一组值,向同一网站上的唯一 URL 发出请求。
每次循环运行时,我都会将响应推送到一个名为“results”的数组中。
当循环结束时,异步函数结束,我添加一个.then 函数,将返回值传递给它。然后我将其记录到屏幕上。
我的问题是 return 语句在我的请求运行之前触发。换句话说,记录了一个空数组,然后所有请求都完成了。
如何在 GET 请求完成后才将我的 for 循环的结果返回给异步函数,并且数组中填充了值?
感谢您的帮助,代码如下:
const axios = require("axios");
var loop = [about,home,products,thanks]
var i;
const results = [];
const test = async () => {
for(i = 0; i < loop.length; i++) {
axios.get(`https://examplewebsite.com/${loop[i]}`)
.then((response,body) => {
results.push(response);
})
.catch((error) => {
console.log(error)
});
};
// THIS IS NOT CORRECT, IT CAUSES MY RESULTS TO BE RETURNED IMMEDIATELY
return results;
}
test().then((results) => {
console.log(results); // Currently outputs --> [ ]
});
【问题讨论】:
-
您缺少
await关键字
标签: javascript node.js asynchronous get axios