节点 JS 根据事件到达恢复执行

Node JS resuming execution based on event arrival

本文关键字:恢复 执行 事件 JS 节点      更新时间:2023-09-26

我有一个 Node JS 应用程序,它侦听从实体 A 的套接字接收的事件,并根据此事件执行操作。此操作包括基于承诺链接对不同实体(包括 A)的调用。

我实际需要实现的是一种机制,用于调用实体 A 中的操作,并根据新事件而不是基于 A 响应执行回调。所以流程将是:

return new RSVP.Promise(function (resolve, reject) {
    run action1();
    .then(function (response) {
        return action2();
    })
    .then(function (response) {
        return action3();
    })
    .then(function (response) {
        // code to wait for an event to arrive and resume this
    })
}

这能实现吗?

你似乎不需要周围的new Promise。假设run_action返回一个承诺,那么只需:

return run_action1()
    .then(function (response) {
        return action2();
    })
    .then(function (response) {
        return action3();
    })
    .then(function (response) {
        return new Promise(function(resolve, reject) {
            listen(resolve);
        });
    })
   .then(somethingElse);