Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to resolve a Promise by user action or manually managed triggers? Yes, so we are able to form editable promises

I want a program to run a chain of actions after certain user action is done. However, part of the chain will need to wait for the resolution of previous Promise OR the fact that user has done some action. Is it possible to make Promise work this way?

I am imagining the ideal program script is like:

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
like image 298
COY Avatar asked Nov 27 '25 10:11

COY


1 Answers

Yes!

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

    function done() {
        resolve();
    }

    function wait() {
        return promise;
    }

    return { done, wait }
}

And use it as you've described in your question.

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

// Somewhere else
userAction.done();
like image 65
Arash Motamedi Avatar answered Nov 28 '25 23:11

Arash Motamedi