javascriptpromisees6-promise

How promise is resolved by function call?


I found this snippet for promise which I can use in Promise.race() to prevent waiting long asynchronous operations if some my code in parallel will be finished faster.

let stopCallback = null;
const stopPromise = new Promise(x => stopCallback = x);

await stopPromise; // promise pending until stopCallback() will be executed somewhere

But I can't fully understand how this Promise exactly works.

Please, can someone explain to me how this promise resolves or give any link to where such usecase is described in detail?


Solution

  • IMO it is clearer if you call x another name :

    let stopCallback = null;
    const stopPromise = new Promise( resolve => stopCallback = resolve);
    

    Indeed, whenever you call stopCallback(), it's equivalent to call resolve() and it resolves the Promise.