【问题标题】:Using Promise.all() in which the the individual promises retry on error使用 Promise.all() ,其中个人承诺重试错误
【发布时间】:2017-02-27 02:37:56
【问题描述】:

我有一组承诺(request-promises),它们被包装在另一种方法中,因此如果发现错误,它们将重试 3 次。那部分工作正常。我想使用 promise.all() 因为我最终会有大量的 http 请求。使用我目前使用的方法,promise.all() 在所有重试尝试完成之前仍然调用它回调函数。有没有办法让我在 promise.all() 回调之前等待所有重试尝试完成。

var http_req = require('request-promise')

function My_Http(retries, options)
{
    return http_req(options)
            .then(data=>{console.log('success')})
            .catch(err => {
                retries > 0 ? My_Http(retries-1, options) :  console.log(err.message)
             })
}

var promises = []
promises.push( My_Http(3, options1))
promises.push( My_Http(3, options2))

promise.all(promises).then( data=> {console.log(data)} )

【问题讨论】:

    标签: javascript node.js http request promise


    【解决方案1】:

    好的,我认为这是一个愚蠢的错误,但可能会让其他人看到,我删除了 My_Http 中的 then 并返回整个三元语句。

    var http_req = require('request-promise')
    
    function My_Http(retries, options)
    {
        return http_req(options)
                .catch(err => {
                    return retries > 0 ? My_Http(retries-1, options) :  console.log(err.message)
                 })
    }
    
    var promises = []
    promises.push( My_Http(3, options1))
    promises.push( My_Http(3, options2))
    
    promise.all(promises).then( data=> {console.log(data)} )
    

    【讨论】:

    • 是的,您必须返回重试的承诺才能正确地链接它。 .then() 并没有阻止重试,它只是阻止您获取返回值,因为您没有从 .then() 返回值。
    • 注意:then 块很好,是你的 catch 块中的 return 产生了影响
    • 首选.map 而不是.push。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2017-05-17
    • 2016-11-25
    • 1970-01-01
    • 2018-07-23
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多