gpt4 book ai didi

javascript - 在 axios 异步调用之外返回数据

转载 作者:行者123 更新时间:2023-12-03 01:45:50 24 4
gpt4 key购买 nike

如何在 for 循环之外返回 stuff 的值。我需要进行 API 调用 i 次并每次存储结果。某处可能有重复的问题和答案,但我找不到它。

function getResponse() {
var stuff = []

for (let i = 0; i < length; i++) {
axios.get(url + i)
.then(res => res.forEach(item => {
stuff.push(item)
}))
}
// How do I return stuff from this function ?
}

console.log(getResponse())

我尝试让这个函数只进行一次调用,然后在另一个调用它的函数中循环,但我得到:

cannot read property then of undefined.

最佳答案

How do I return stuff from this function ?

你不能。就像“我想要明天的报纸”。那也行不通。您必须等到第二天才能阅读报纸,或者就您而言,直到所有数据都到达浏览器。您不能直接返回数据,而是一个Promise,它将在某个时候传递数据。在您的情况下,您可以使用 Promise.all 将 promise 数组统一为解析为数组的 promise :

function getResponse() {
const promises = [];

for (let i = 0; i < length; i++) {
promises.push(axios.get(url + i));
}

return Promise.all(promises)
.then(results => [].concat(...results));
}

所以现在如果你这样做:

console.log(getResponse())

你得到了一个 promise 。要获取实际数据,您必须等待数据到达:

getResponse().then(console.log);

关于javascript - 在 axios 异步调用之外返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50646301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com