gpt4 book ai didi

javascript - 如何运行 promise 数组

转载 作者:行者123 更新时间:2023-11-30 15:28:26 25 4
gpt4 key购买 nike

在此函数中,在内联数组完成之前调用回调。仅当 inline 具有所有值时如何调用它?

function inlineSearch( search, callback ) {
const inline = []

mal.quickSearch( search ).then( response => {
response.anime.forEach( anime => {
anime.fetch( ).then( json => {
inline.push( replyInline( json ) )
})
})
.then( callback( inline ) )
} )
}

response.anime 是一个指向另一个 json 对象的 json 对象数组,这就是为什么我需要获取它以便获得正确的 json。

而且,replyInline 是一个只接受 json 并返回另一个的函数。

mal = 我的动漫列表 API

最佳答案

Array#mapPromise.all 一起使用 - 也不需要那个 inline var

如果您必须使用回调,那么下面的方法应该有效

function inlineSearch(search, callback) {
mal.quickSearch( search )
.then(response =>
Promise.all(response.anime.map(anime =>
anime.fetch()
.then(json => replyInline(json))
))
)
.then(results => callback(results));
}

用法:

inlineSearch("whatever", function(results) {
// do whatever with results
});

或者,如果没有回调,上面的代码可以这样写:

function inlineSearch(search) {
// note the return
return mal.quickSearch( search )
.then(response =>
Promise.all(response.anime.map(anime =>
anime.fetch()
.then(json => replyInline(json))
))
);
}

用法:

inlineSearch("whatever").then(results => {
// do whatever with results
});

关于javascript - 如何运行 promise 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42603632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com