Logic
JavaScript
6 May 2023
A Promise is an object representing the eventual completion or failure of an asynchronous operation. Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.
Essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. Chained in Sequence, with no parameter passing.
1doSomething().then(function () { 2 return doSomethingElse(); 3});
This executes doSomething(), then when it resolves, it executes doSomethingElse() and the resolved value of the promise chain is the resolved value or return value of doSomethingElse(). No arguments are passed to doSomethingElse(). Chained in Sequence, with no parameter passing.
1doSomething().then(function () { 2 doSomethingElse(); 3});
Same as option 1, except the resolved value of the promise chain is undefined because there is no return value from the .then() handler. Any return value from doSomethingElse(), whether a promise or a value is ignored.
1doSomething().then(doSomethingElse());
This is pretty much never what you want. This executes doSomething() and then, before doSomething() has resolved, it also executes doSomethingElse() and passes the return value from doSomethingElse() as the .then() handler. This is a coding mistake unless doSomethingElse() returns a function to be used as the .then() handler.
1doSomething().then(doSomethingElse);
This is the same as option 1. except that the resolved value from doSomething() is passed as the first argument to doSomethingElse(val). This is structurally the same as this:
1doSomething().then(function () { 2 return doSomethingElse(); 3});