javascript - 如何处理 Promise 中的异步代码?

标签 javascript es6-promise

基本上,我有一个 promise ,在一个循环中有多个 API 调用,将结果附加到一个数组中,而该数组又由 Promise.all 解析。 。但是,代码似乎永远不会将数组的值返回到 Promise.all并且只返回 Unresolved promise 。

这是复制的代码-

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

输出:[undefined, undefined]

如何确保数组在继续打印之前已完全解析?

最佳答案

Promise.all 需要一个 Promise 数组,而 map 回调函数应返回将映射到新数组的值。

您实际上传递了一个 undefined object 的数组,因为您的 map 函数根本不返回任何内容。

您应该返回 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

关于javascript - 如何处理 Promise 中的异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230914/

相关文章:

javascript - 检查 JavaScript 中是否存在对象

javascript - HTML - 折叠的导航菜单不显示菜单项

javascript - jQuery.when 接受原生 Promise 对象吗?

javascript - 如何在 bulkwrite 的 for 循环中设置异步/等待?

javascript - 检查文件何时被拖到网站

javascript - vbscript Mid 函数的 javascript 等效函数是什么?是 substring() 还是 substr()?

javascript - 如何让div滚动滑动?

javascript - 为什么我的 promise 没有兑现?

javascript - Promise 子进程通信

javascript - Google Maps Geocoder API 的 promise