简体   繁体   English

使用Promise将元素推入数组

[英]Pushing an Element into an Array Using Promises

When I console.log my array it remains empty, so I am failing to push the element into the array with my code. 当我console.log我的数组时,它保持为空,因此我无法使用我的代码将元素推入数组。 I can do it outside of a function, but do not know what I am doing wrong here with the promises. 我可以在函数外部执行此操作,但是不知道我在诺言中做错了什么。 I am new to promises. 我是新来的诺言。 Thanks for any tips: 感谢您的提示:

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? 
}

Your issue is the order of resolution. 您的问题是解决的顺序。 Namely, when your code executes, here is what happens: 即,当您的代码执行时,将发生以下情况:

0.) Arr = [] 0.)Arr = []

1.) Start for loop 1.)开始循环

2.) Initiate promise 2.)发起承诺

3.) log arr 3.)日志地址

4.) loop finishes 4.)循环完成

5.) log arr 5.)日志地址

6.) At some undefined point in the future, a few milliseconds later, your promises resolve, one at the time, each adding the element to the array. 6.)在将来的某个不确定的时间点(几毫秒后),您的承诺会一次解决,每次都会将元素添加到数组中。

Try capturing the promises in an array and using 尝试捕获数组中的promise并使用

Promise.all(promiseArr).then(()=>{
    console.log(arr)
})

Promise.all will wait till all the promises in the array have finished before executing, so you'll be able to log your completed array. Promise.all将等到数组中的所有promise完成后再执行,因此您将能够记录已完成的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM