简体   繁体   English

如何在Promise中处理异步代码?

[英]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 . 基本上,我可以保证在一个循环中具有多个API调用,并将结果附加到数组中,然后由Promise.all解决。 However, the code never seems to return the values of the array to Promise.all and just returns unresolved promises. 但是,代码似乎从不将数组的值返回给Promise.all而仅返回未解决的Promise.all

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 https://jsbin.com/vemasopojo/edit?js,控制台

Output: [undefined, undefined] 输出: [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. Promise.all期望一个promises数组,并且map回调函数应该返回将被映射到新数组的值。

You are actually passing an array of undefined objects, because your map function isn't returning anything at all. 实际上,您正在传递未定义对象的数组,因为map函数根本不返回任何东西。

You should return the fetch call to make it work 您应该返回fetch调用以使其正常工作

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 https://jsbin.com/zeyoxazova/2/edit?js,控制台

You are calling resolve outside the inner asynchronous call, which means it is being called prematurely. 您在内部异步调用外部调用resolve,这意味着它被过早调用。

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. 您的问题是map函数内部缺少return语句。 With no return statement, it returns undefined. 没有return语句,它将返回undefined。 Just put return in front of fetch: 只需将return放在获取之前:

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

You should also avoid using the Promise constructor. 您还应该避免使用Promise构造函数。 You don't need it there and can just directly return the Promise that Promise.all creates: 您在那里不需要它,可以直接返回Promise.all创建的Promise:

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);
}

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

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