Before promises, the only native way of handling asynchronous events were callback functions, which in more complicated cases resulted in a nested pyramid of callbacks (“callback hell”), a code that is hard to read and less composable.
Let’s take a look at the code above.
We created two functions,
Creating the Promise
myPromiseCreator() function creates, and returns a Promise object. To create a Promise object, we need to pass a callback function as an argument to the constructor of the Promise object:
new Promise( (resolve,reject) =>
// The body of the arrow function. Do some async stuff here, and return the result
Notice that we are using ES6’s new arrow function shorthand for declaring our function that we are passing in to the Promise object constructor as an argument.
Our promise object‘s constructor receives a callback function as an argument, which in turn takes two arguments,
reject, which are both callback functions as well.
Inside our function we set a conditional case which detects if the async event (in our case a
setTimeout() function) took more than 3 seconds.
If our async operation took more than 3 seconds, we reject the promise, otherwise we resolve it. Notice, that instead of a return statement, we return value from our Promise with the
Handling the Promise
handleMyPromise() function is responsible for handling our Promise.
It initiates the creation of the Promise object (and starts the async process) by calling the
myPromiseCreator(), and calls the Promise‘s built-in
then() function on the Promise object returned by our
myPromiseCreator(), which handles the case of a resolved Promise (a success).
We also call the Promise‘s built-in
catch() function on our returned Promise object, which handles the case of a rejected Promise (a failure of the async operation). Remember, that we created the logic in the
myPromiseCreator() function to reject or resolve our Promise.
So this is our logic to handle our returned Promise, but there is still an important part within our
handleMyPromise() function after(!) our Promise handling logic at line:18:
document.write('Single thread continued before our Promise returned!');
'Single thread continued before promise resolved!'.
handleMyPromise() function in the last 4 lines of our code).
Author: Nandor Persanyi