Promise in JavaScript is a commitment that sometime in the future, your code will get a value from some operation (like reading a file or getting JSON from a Web site) or your code will get an error from that operation (like the file doesn't exist or the Web site is down).Promise objects with the Promise constructor:
resolve() transitions the Promise object to the fulfilled statereject() transitions the Promise object to the rejected statenew Promise((resolve, reject) => { // do some async stuff // call resolve(value) to make the Promise succeed // call reject(reason) to make the Promise fail });
Promises can exist in three states:
Promise object has not resolved. Once it does, the state of the Promise object may transition to either the fulfilled or rejected state.Promise represented succeeded and your success handler will get called. Now that it's fulfilled, the Promise:
Promise.resolve(value)Promise object transitions to the rejected state and no error handler exists for the then, then that then is skipped altogether.Promise objects have the following methods available on them so that you can handle the state change from pending to either fulfilled or rejected.
then(successHandler, errorHandler) is a way to handle a Promise when it leaves the pending state.Success Handler is a function that has one parameter, the value that a fulfilled Promise has.Error Handler is a function that has one parameter, the reason that the Promise failed.then()Promise comes out of the pending state.Promise that transitions out of it's pending state when the then that created it completeserror handler (essentially saying, if this then does not resolve, then this error handler will do something.)then()thens will evaluate as:
then: I do not have an error handler. I will pass the error on and not run the success handler.then: I do not have an error handler. I will pass the error on and not run the success handler.then: I have an error handler and will run it.Promise when the Promise object transitions to the fulfilled state. If an error condition occurs, them the error handler of the then is called.Promise object transitions to the rejected state and no error handler exists for the then, then that then is skipped altogether.Promise object transitions to the fulfilled state and the next success handler is called.catch()then with a success and error handler, you can use the similar catch method that takes just an error handler.promiseFunction("print") .then(res => res) .then(res => res) .then(() => console.log(“anonymous function text”)) .catch(reason => console.err("Badness happened", reason));
catch doesn't throw an exception, then it returns a Promise in a fulfilled state with whatever the return value is, just like the error handler of a then.Promise.all()Promise object in the pending state colloquially called a "super promise".Promise values into Promise objects that are immediately in the fulfilled state.Promises in the array transitions to the rejected state, then the "super promise" transitions to the rejected state with the same reason that the inner Promise object failed.Promise objects in the array transition to the fulfilled state, then the "super promise" transitions to the fulfilled state with a value of an array populated with all of the resolved values of the original array.asyncasync will make it implicitly return a Promise if it doesn’tawaitPromise is awaited, execution of the containing async function will pause until the promise is fulfilledawait expression will evaluate to the resolved value of the Promiseawait outside of an async function will result in a SyntaxErrortry…catch pattern to handle errors when the Promise is rejectedfunction wrapper() { promise1 .then(res1 => { console.log(res1); return promise2; }) .then(res2 => { console.log(res2); return promise3; }) .then(res3 => { console.log(res3); }); }
with async/await…
async function wrapper() { console.log(await promise1); console.log(await promise2); console.log(await promise3); console.log(await promise4); }
fetchfetch API to make Promise-based API callsfetch takes 2 parameters:
Promiseconst fetch = require('node-fetch'); const MOVIE_API_KEY = "some-api-key"; const url = `https://omdbapi.com/?apikey=${MOVE_API_KEY}&t=fight+club` fetch(url) .then(res => res.json()) .then(json => console.log(json.Actors)) .catch(reason => console.log('rejected because', reason))