resolve() and reject()

Within the promise, resolve() or reject() should be called to allow the promise to be chained later. When called, resolve() or reject() does not return the function immediately, but will signal the promise to pass on the resolved or rejected value to 'then()' later. Any error should be handled in the 'errorCallback' of the next then(), or caught later within the next catch() (not necessarily following immediately) along the chain. An unhandled/uncaught error will halt the entire program.In short, there are three identical ways to catch an error:

with the second callback to .then()

with the only callback to .catch()

within regular try{...}catch(e){...}blocks


RESETRUNFULL
<!DOCTYPE html><html><body><script>

var p = new Promise((resolve,reject)=>{       // Promise executed immediately at the time of creation
   resolve(1,999);
  console.log(0);                  // 0. resolve() does not return the function immediately});console.log('START');  // logged after 0p.then(
   (a,b)=>{console.log(a); throw 'e1';}, // 1
   ()=>{console.log(2); }                      // (skipped)).then(
   ()=>{console.log(3)},                       // (skipped)
   ()=>{console.log(4); return 5;}         // 4).then(
   n=>{console.log(n); undefinedFn();},// 5
   ()=>{console.log(6)}                        // (skipped)).then(
   ()=>{console.log(7)}                        // (skipped)).then(
   ()=>{console.log(8)}                        // (skipped)).catch (
   console.log                                       // ReferenceError...).then(
   ()=>{console.log(9); },                     // 9
   ()=>{console.log(10); }                    // (skipped)).then(
   ()=>{console.log(11); throw 'e2';},   // 11
   ()=>{console.log(12); }                    // (skipped));  // ERROR: Uncaught (in promise) e2

</script></body><html>

A promise is executed at the moment of creation. To delay its execution, return it in a function.


RESETRUNFULL
<!DOCTYPE html><html><body><script>

function p(){
    return new Promise(resolve=>{console.log(1); resolve();});}f = f1 => f2 => f3 =>{p().then(()=>console.log(2));}f()()();console.log(3);// 1 3 2// At first .then() is pushed to the microtask queue, which // will be run after the ‘main execution’ ends, ie. call stack // becomes completely empty

</script></body><html>

As we can see above, Promise provides a neat and flexible means to control the order of execution in a program, by maintaining the order in a separate microtask queue (aka. job queue), in addition to the macrotask queues (aka. task queue) and the call stack.

You can even resolve a promise upon a user-generated event such as a click on a button.
RESETRUNFULL
<!DOCTYPE html><html><body><script>

<!DOCTYPE html><html><body><input type="button" value="now" onclick="R(1)"/><script>var R;function deferred_promise(){    return new Promise(resolve=>{        R=resolve;    })}deferred_promise().then(alert);</script></body></html>

</script></body><html>