是否可以通过用户操作或手动管理的触发器来解决 Promise?是的,所以我们能够形成可编辑的承诺

COY*_*COY 3 javascript promise

我希望程序在完成某些用户操作后运行一系列操作。然而,链的一部分将需要等待先前 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
Run Code Online (Sandbox Code Playgroud)

Ara*_*edi 6

是的!

function createUserAction() {
    let resolve = undefined;
    const promise = new Promise(r => { resolve = r });

    function done() {
        resolve();
    }

    function wait() {
        return promise;
    }

    return { done, wait }
}
Run Code Online (Sandbox Code Playgroud)

并按照您在问题中所描述的方式使用它。

const userAction = createUserAction();
var coreTrigger = Promise.any([normalAsyncRequest, userAction.wait()]);
coreTrigger.then(res=>{
  // the followup action
});

// Somewhere else
userAction.done();
Run Code Online (Sandbox Code Playgroud)

  • 你的回答告诉了我我所需要的绝妙想法,即我们可以通过解析器将“解决”和“拒绝”传递给外界。谢谢你! (2认同)