我希望程序在完成某些用户操作后运行一系列操作。然而,链的一部分将需要等待先前 Promise 的解决或用户已执行某些操作的事实。 Promise 可以这样工作吗?
我想象理想的程序脚本是这样的:
var coreTrigger = Promise.any([normalAsyncRequest, userAction]);
coreTrigger.then(res=>{
// the followup action
});
...
// somewhere far away, or in developer console
userAction.done(); // I want this can be one possible path to trigger the followup action
Yes!
function createUserAction() {
let resolve = undefined;
const promise = new Promise(r => { resolve = r });
function done() {
resolve();
}
function wait() {
return promise;
}
return { done, wait }
}
并按照您在问题中所描述的方式使用它。
const userAction = createUserAction();
var coreTrigger = Promise.any([normalAsyncRequest, userAction.wait()]);
coreTrigger.then(res=>{
// the followup action
});
// Somewhere else
userAction.done();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)