With Node.js you have the ability to make promises, but what is a promise?
Here is a definition of a node.js promise
‘A promise is an abstraction for asynchronous programming. It’s an object that proxies for the return value or the exception thrown by a function that has to do some asynchronous processing’
The core idea behind promises is that a promise represents the result of an asynchronous operation. A promise is in one of three different states:
- pending – The initial state of a promise.
- fulfilled – The state of a promise representing a successful operation.
- rejected – The state of a promise representing a failed operation.
Once a promise is fulfilled or rejected, it is immutable (i.e. it can never change again).
So how do we create a Promise on Node.js?
Create a Promise
We can create a promise in our Node JS program using the new constructor.
var myPromise = new Promise(function(fulfill, reject){ .... })
So myPromise is a Promise type object which allows us to use it for later.
Let’s get down to writing a small sample application to show a promise fully working
Promise in Action
We will make a promise which will wait for 2 seconds and then update a message and display the message. Once the promise has been completed everything will finish.
Just so we can see the order of tasks we will add a console.log at different points of the application.
function doSomething(message){
return new Promise(function (fulfill){
setTimeout(() => {
fulfill(message + " fulfilled");
}, 2000);
});
}
doSomething('promise')
.then(data => {
console.log(data);
});
console.log("Will hit here first, then wait for two seconds");
When you run this you should get the following results:
Will hit here first, then wait for two seconds promise fulfilled
Okay so far?
Async
Consideration should be given to using Async/Await in place of .then .catch.
The Async pattern is a more preferable way to consume promises, which makes your promise consuming code more readable and easier, especially when dealing with loops and other complexities.
function doSomething(message){
return new Promise(function (fulfill){
setTimeout(() => {
fulfill(message + " fulfilled");
}, 2000);
});
}
doSomething('first promise')
.then(data => {
console.log(data);
});
(async function read() {
const data = await doSomething('second promise');
console.log(data);
}
)();
console.log("Will hit here first, then wait for two seconds");
Much nicer, and easier to read too.