蓝鸟取消等待中

时间:2019-06-04 11:07:14

标签: javascript promise bluebird cancellation

此代码正常工作:

let promise;
try {
    promise = parent();
    //but I want: await parent();
    await continueStack();
} catch (e) {
    console.log('Caught error in endpoint');
}

eventBus.on('stop::all', () => {
    console.warn('Caught stop::all event');
    promise.cancel();
});

它取消了程序其他部分发出的事件的承诺。我的问题是我不能拥有await parent(),因为那时尚未执行监听事件。如果我改成这样:

let promise;
eventBus.on('stop::all', () => {
    console.warn('Caught stop::all event');
    promise.cancel();
});

try {
    promise = await parent();
    await continueStack();
} catch (e) {
    console.log('Caught error in endpoint');
}

那我有错误

  

TypeError:无法读取未定义的属性“取消”

,它将崩溃,并且continueStack()从未执行。我该如何调和这些?


我已经用上述场景创建了整个示例:

https://gist.github.com/BorysTyminski/147dc2e0c44c8d64386253d563ff6db4

要运行它,您需要获取两个文件,安装package.json依赖项并运行cURL / Postman请求GET到localhost:5000 / test

1 个答案:

答案 0 :(得分:1)

您可以通过将promise变量设置为parent,然后等待它来完成此操作:

const EventEmitter = require('events');
const Promise = require('bluebird');

Promise.config({
  cancellation: true,
})
const parent = new Promise(resolve => {
  setTimeout( () => {
    resolve();
  }, 100);
});

const continueStack = new Promise(resolve => {
  setTimeout( () => {
    resolve();
  }, 100);
});

let promise;

const emitter = new EventEmitter();

emitter.on('stop', function() {
  if(promise && promise.cancel){
    promise.cancel();
    console.log('promise cancelled');
  } else {
    console.log('somehow promise was not properly set at this point');
  }
});

setTimeout(_ => {
  emitter.emit('stop');
}, 80);

async function operation() {
  try {
  promise = parent;
  await promise;
  console.log('after promise. This log should never appear.');
  await continueStack;
    console.log('after wait 2. This log should never appear.');
  } catch(e) {
    console.log('Even if the promise is cancelled, this is not called.');
  }
}

operation();

(使用该节点运行该代码段只会记录“已取消承诺”):在执行异步函数内的await promise之后什么都没有。)

一些注意事项:

  • 需要Promise.config才能将cancellable设置为true。
  • await不像睡觉。它不会阻止javascript线程,事件监听器或任何事件发射器。它只是确保await之后的代码将等待已承诺的等待。但这仅在异步函数的上下文中。

  • 取消Promise不会触发捕获处理程序。这让我感到困惑,但我想这就是它的工作原理。