32
loading...
This website collects cookies to deliver better user experience
callback hell
). Since ES6 promises are a standard part of Javascript and with async/await
(ES8) they are used in async functions .fetch('url')
.then(() => fetch('url'))
.then(() => fetch('url'))
.then(() => fetch('url'))
.then(() => fetch('url'))
.then(() => console.log('all done'))
.catch(err => console.log(err));
fetchCallback('url', err => {
if (err) return console.log(err);
fetchCallback('url', err => {
if (err) return console.log(err);
fetchCallback('url', err => {
if (err) return console.log(err);
fetchCallback('url', err => {
if (err) return console.log(err);
console.log('all done');
});
});
});
});
fetch('url')
.then(response => console.log(response.status))
.catch(error => console.log(error));
fetch
returns a Promise, and the Promise API allows us to chain the then
and catch
handlers.catch
is best practice.In future versions of Node.js, unhandled Promise rejections will crash your application with a fatal exception.
Promise
constructor:const myPromise = new Promise((resolve, reject) => {
// do something asynchronous
});
then
and catch
methods.const fs = require('fs');
const myPromise = new Promise((resolve, reject) => {
fs.readFile('example.json', (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
});
myPromise
.then(data => console.log(data))
.catch(err => console.log(err));
fs.readFile
in a Promise
. If reading the file encountered an error, we pass it to reject, otherwise we pass the data obtained from the file to resolve. Calling resolve
passes the data to our .then
handler, and reject
passes the error to the .catch
handler.fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log(err));
fetch
function returns a promise, which will either resolve or reject. The attached then
handles the response by fetch, when it resolves. The response body has a json
method for parsing the response from JSON to an object. The json
method returns a promise of its own, which handle by attaching another then
handler, and in case of error we attach a catch
handler and log the error.then
and catch
methods to a Promise in order to execute code when the state changes.