javascript - 如何在不知道首先执行哪个 then() 的情况下返回已解决的 promise

标签 javascript node.js

我有一个方法可以返回一个 promise 。如下所示,有两个then()语句。它们中的每一个都包含对单选按钮的引用,以及将根据所选单选按钮执行的特定方法。

我事先不知道将选择哪个单选按钮。我想要实现的是,该方法应根据所选的单选按钮返回已解决的 promise 。例如,如果我选择 radioButton1,则不应执行第一个 then(),并且该方法应该为 radioButton1 返回已解决的 promise 。

如果我选择 radioButton2,则不应执行第二个 then() 并且该方法应该为 radioButton2 返回已解决的 promise 。

我希望我能清楚地解释我的观点。请让我知道如何实现它。

代码1:

initComponents() {
return Promise.resolve()
  .then(() => this.getRadioButton1().on(RState.EVENT_ACTION, (action) => {
    this.onRadioButton1Changed.bind(this);
  }))
  .then(() => this.getRadioButton2().on(RState.EVENT_ACTION, (action) => {
    this.onRadioButton2Changed.bind(this);
  }));
}

最佳答案

通常在这种情况下你会使用 Promise.race ,它订阅你给它的数组中的 promise ,并根据它们中的第一个来结算(解决或拒绝):

initComponents() {
  return Promise.race([
    new Promise(resolve => {
        this.getRadioButton1().on(RState.EVENT_ACTION, (action) => {
          this.onRadioButton1Changed.bind(this); // ???
          resolve(this); // or `resolve(action);` or `resolve({button: this, action});`
        })
    }),
    new Promise(resolve => {
        this.getRadioButton2().on(RState.EVENT_ACTION, (action) => {
          this.onRadioButton2Changed.bind(this); // ???
          resolve(this); // or `resolve(action);` or `resolve({button: this, action});`
        })
    })
  ]);
}

...但这看起来不像是 promises 的用例;事件不止一次发生,但 promise 只被确定一次。另外,this.onRadioButton1Changed.bind(this); 是空操作,您不会在任何地方保存绑定(bind)函数。

或者避免重复:

const promiseForButtonActionWithBind = (button, fn) => new Promise(resolve => {
  button.on(RState.EVENT_ACTION, (action) => {
    fn.bind(this); // ???
    resolve(this); // or `resolve(action);` or `resolve({button, action});`
  })
});

然后

initComponents() {
  return Promise.race([
    promiseForButtonActionWithBind(this.getRadioButton1(), this.onRadioButton1Changed),
    promiseForButtonActionWithBind(this.getRadioButton2(), this.onRadioButton2Changed)
  ]);
}

关于javascript - 如何在不知道首先执行哪个 then() 的情况下返回已解决的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50872968/

相关文章:

javascript - 从同一来源重新加载 <img> 元素

javascript - 来自 AngularJS 的 NodeJS HTTP 请求

javascript - 如何从 Vaadin 获取数据到 HTML/Jsp 文件?

javascript - jQuery 验证提交表单 ActionController::ParameterMissing

javascript - p :commandButton only works with two clicks (JSF 2. 2 错误?)

javascript - .call(this) JavaScript 中的习语

node.js - 如何在 Google App Engine 上运行迁移

javascript - 如何从路由文件中在 socket.io 中发出事件?

node.js - Sequelize DataTypes.STRING 的意外标记

javascript - 如何使用 feather js 更新 html 文档?