蓝鸟承诺在拒绝时不会短路

Bluebird promise failing to short circuit on reject

也许我只是不理解承诺,但我以前使用过这种模式并且从未遇到过问题。在节点中使用蓝鸟。

我有这个功能被击中:

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 并抛出

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

基本上它一直在解决问题。

我的印象是,promise 应该在拒绝时立即短路,并将拒绝作为对 promise 的决议通过。我是不是误会了?

是的,你误会了。 reject(…) 不是语法(就像 一样)并且不像 return 语句那样退出函数。这只是一个正常的函数调用 returns undefined.

你应该使用

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

拒绝的 "short-circuiting" 行为归因于承诺链。当你有

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

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