基本上,我有一个 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();
})
})
关于javascript - 如何处理 Promise 中的异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53230914/