我有一个方法可以返回一个 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/