【问题标题】:How to run promise array如何运行承诺数组
【发布时间】:2017-07-25 00:35:31
【问题描述】:

在这个函数中,回调是在内联数组完成之前调用的。仅当 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

【问题讨论】:

  • 你看过Promise.all()吗?
  • 你需要Promise.allrepsonse.anime.map
  • 顺便说一句,最后一个.then 肯定是错误的,因为.then 需要一个函数作为参数
  • @nnnnnn 我试过但没用
  • 不,你没有尝试,因为你的代码没有使用它

标签: javascript arrays json node.js promise


【解决方案1】:

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

【讨论】:

  • 非常感谢,没有回调代码工作得很好。您帮助我解决了近五天以来我一直难以理解的一件事。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 2017-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多