【问题标题】:Bluebird promise failing to short circuit on reject蓝鸟承诺在拒绝时无法短路
【发布时间】:2018-09-12 13:54:05
【问题描述】:

也许我只是不理解承诺,但我以前使用过这种模式并且从未遇到过问题。在节点内使用 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 并抛出

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

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

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

【问题讨论】:

  • reject 没有退出函数,在 if 中添加一个 return,另外,你不使用 resolve,所以你永远不会从 getStores() 得到结果
  • 你从来没有打电话给resolve

标签: node.js promise bluebird


【解决方案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 的回调。

【讨论】:

    猜你喜欢
    • 2015-04-13
    • 1970-01-01
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2014-11-06
    • 2015-09-06
    相关资源
    最近更新 更多