当我 console.log 我的数组时,它仍然是空的,所以我无法用我的代码将元素插入数组。我可以在函数之外做,但不知道我在这里做错了什么 promise 。我是新来的 promise 。感谢您的任何提示:
function fetchApiData(num) {
let arr = [];
for(let i = 0; i < num; i++) {
fetch('https://dog.ceo/api/breeds/image/random')
.then(response => response.json())
.then(responseJson => console.log(responseJson.message))
.then(responseJson => arr.push(responseJson.message));
console.log(arr);
}
console.log(arr);
// how do I change console.log to push value into an array?
}
最佳答案
您的问题是解决顺序。也就是说,当您的代码执行时,会发生以下情况:
0.) Arr = []
1.) 开始for循环
2.) 发起 promise
3.) 日志记录
4.) 循环结束
5.) 记录 arr
6.) 在未来某个未定义的时间点,几毫秒后,您的 promise 会解决,一次一个,每个都会将元素添加到数组中。
尝试在数组中捕获 promise 并使用
Promise.all(promiseArr).then(()=>{
console.log(arr)
})
Promise.all 将等到数组中的所有 promise 都完成后再执行,因此您将能够记录完成的数组。
关于javascript - 使用 Promises 将元素推送到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52996305/