Promises
Learn how ES2015 solves the problem of callback hell and the Pyramid of Doom. Promises are now used everywhere in asynchronous code and are part of modern and future JavaScript.
Preface: A Note
Throughout this lesson and future lessons regarding asynchronous code, several code blocks will be runnable. The code in the blocks is not runnable by itself; if you try to paste it in another JavaScript evaluator, it will not work.
There is hidden code prepended in each block. These blocks are meant only to demonstrate what an actual application using asynchronous code might look like.
Introduction
We come now to a solution to the pyramid of doom from earlier. Promises are still entirely callback-based, but they give us a nice syntax wrapper around the callbacks to make it easier to read asynchronous code.
Standard Callbacks
Starting with callbacks, let’s review a common pattern of asynchronous code execution. This is the same code found in the earlier lesson. Here’s the situation we’re in.
A user launches a request from thier browser. When the server receives the request, the server needs to read data from a file, write it to another file, and then send a response notifying the user when it’s all done.
Remember that onRequest
is called with this as the request
parameter.
request = {
fileToRead: 'readFrom.txt',
fileToWrite: 'writeTo.txt'
};
Get hands-on with 1400+ tech skills courses.