蓝鸟承诺拒绝短路

时间:2018-04-03 09:31:39

标签: node.js promise bluebird

也许我只是不理解承诺,但我之前使用过这种模式,从来没有遇到过问题。在节点中使用bluebird。

我有这个被击中的功能:

function getStores() { 
    return new Bluebird((resolve, reject) => {
        return Api.Util.findNearbyStores(Address,(stores) => {
             if (!stores.result) {                 
                 console.log('one')
                 reject('no response');
                 console.log('two')
             }

             const status = stores.results.status
        })
    })
}

然后点击我的两个日志,继续经过if和throws

 'one'
 'two'
 TypeError: Cannot read property 'Status' of undefined

基本上它一直走在决心之上。

我的印象是承诺应该立即在拒绝时短路并通过拒绝作为承诺的决议。我误解了这个吗?

1 个答案:

答案 0 :(得分:1)

是的,你误解了这一点。 reject(…)不是语法(就像resolve(…) isn't either),并且不像退出函数的return语句那样。这只是一个返回undefined的普通函数调用。

您应该使用

if (!stores.result) reject(new Error('no response'));
else resolve(stores.results.status);

拒绝的“短路”行为归因于承诺链。当你有

getStores().then(…).then(…).catch(err => console.error(err));

然后拒绝getStores()返回的承诺将立即拒绝链中的所有承诺并触发catch处理程序,忽略传递给then的回调。

相关问题