Node.js Asynchronous programming Native Promises



Promises are a tool for async programming. In JavaScript promises are known for their then methods. Promises have two main states 'pending' and 'settled'. Once a promise is 'settled' it cannot go back to 'pending'. This means that promises are mostly good for events that only occur once. The 'settled' state has two states as well 'resolved' and 'rejected'. You can create a new promise using the new keyword and passing a function into the constructor new Promise(function (resolve, reject) {}).

The function passed into the Promise constructor always receives a first and second parameter usually named resolve and reject respectively. The naming of these two parameters is convention, but they will put the promise into either the 'resolved' state or the 'rejected' state. When either one of these is called the promise goes from being 'pending' to 'settled'. resolve is called when the desired action, which is often asynchronous, has been performed and reject is used if the action has errored.

In the below timeout is a function that returns a Promise.

function timeout (ms) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve("It was resolved!");
    }, ms)

timeout(1000).then(function (dataFromPromise) {
  // logs "It was resolved!"


console output

// << pauses for one second>>
It was resolved!

When timeout is called the function passed to the Promise constructor is executed without delay. Then the setTimeout method is executed and its callback is set to fire in the next ms milliseconds, in this case ms=1000. Since the callback to the setTimeout isn't fired yet the timeout function returns control to the calling scope. The chain of then methods are then stored to be called later when/if the Promise has resolved. If there were catch methods here they would be stored as well, but would be fired when/if the promise 'rejects'.

The script then prints 'waiting...'. One second later the setTimeout calls its callback which calls the resolve function with the string "It was resolved!". That string is then passed into the then method's callback and is then logged to the user.

In the same sense you can wrap the asynchronous setTimeout function which requires a callback you can wrap any singular asynchronous action with a promise.

Read more about promises in the JavaScript documentation Promises.