javascript - Bluebird 取消等待

标签 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();
});

它正在取消对程序其他部分发出的事件的 promise 。我的问题是我不能有 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: Cannot read property 'cancel' of undefined

它崩溃了,continueStack() 永远不会执行。我应该如何调和这些?


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

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

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

最佳答案

您可以通过将 promise var 设置为 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();

(使用节点运行该代码片段只会记录“promise cancelled”):在执行异步函数内的 await promise 之后没有任何内容。

一些注意事项:

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

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

关于javascript - Bluebird 取消等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442644/

相关文章:

angularjs - Angularjs Bootstrap 模式窗口,在ok()上保存事件并更新父范围的事件列表

javascript - AngularJS - 如何取消 promise ?

javascript - 使用可读的函数名称扁平化 promise 链

node.js - Node bluebird 中的 Q.ninvoke 替换

javascript - 如何防止嵌套的 Promise 挂起?

具有字边界要求的 JavaScript 正则表达式

javascript - @Html.CheckBoxFor() - 更改复选框标签颜色

javascript - 从服务器加载 html 文件/脚本

javascript - Javascript promise return 最佳实践

php - 如何使用ajax或jquery验证类型radio的答案