简体   繁体   中英

How do I handle asynchronous code within a promise?

Basically, I have a promise that has multiple API calls in a loop that appends the results into an array, which in turn is being resolved by Promise.all . However, the code never seems to return the values of the array to Promise.all and just returns unresolved promises.

Here's the reproduced code-

function func1(data) {

return new Promise(function(resolve, reject) {
  var arr1 = data.split(". ");
  var another_arr = arr1.map(function(sent) {
    fetch('https://pokeapi.co/api/v2/pokemon/1/')
      .then(function(response) {
        return response.json();
      })
  })
  resolve(Promise.all(another_arr))
})
}

function func_main() {
  var some_string = "This is a sentence. This is another sentence."
  this.func1(some_string).then(function(value) {
  console.log(value)
})
}

func_main()

https://jsbin.com/vemasopojo/edit?js,console

Output: [undefined, undefined]

How do I ensure that the array is completely resolved before moving on to print it?

Promise.all expects an array of promises and map callback function should return the value that will be mapped to the new array.

You are actually passing an array of undefined objects, because your map function isn't returning anything at all.

You should return the fetch call to make it work

var another_arr = arr1.map(function(sent) {
   return fetch('https://pokeapi.co/api/v2/pokemon/1/')
    .then(function(response) {
      return response.json();
    })
  })

https://jsbin.com/zeyoxazova/2/edit?js,console

You are calling resolve outside the inner asynchronous call, which means it is being called prematurely.

Try this instead:

function func1(data) {
  return new Promise(function(resolve, reject) {
    var arr1 = data.split(". ");
    var another_arr = arr1.map(function(sent) {
      fetch('https://pokeapi.co/api/v2/pokemon/1/')
        .then(function(response) {
          resolve(response.json())
      })
    })
  })
}

It feels like there should be a more elegant way to do this, but this should get you the data you are looking for, at any rate.

Your problem is a missing return statement inside the map function. With no return statement, it returns undefined. Just put return in front of fetch:

return fetch('https://pokeapi.co/api/v2/pokemon/1/')
  .then(...

You should also avoid using the Promise constructor. You don't need it there and can just directly return the Promise that Promise.all creates:

function func1(data) {
  var arr1 = data.split(". ");
  var another_arr = arr1.map(function(sent) {
    return fetch('https://pokeapi.co/api/v2/pokemon/1/')
      .then(function(response) {
        return response.json();
      });
    });
  return Promise.all(another_arr);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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