DEV Community

Mahesh
Mahesh

Posted on

Understanding JavaScript Promises

1. Need for Promises

When we send a network-request, we have to wait for some time to get response from the server.

But as JavaScript is a synchronous-language, it does not wait to receive a response after some time with normal function call.

Hence, Promises are introduced. Promises gives a promise to code written after it, to provide value after some time.

2. Promise Creation

Promise() constructor is used for Promise creation.

Syntax

new Promise(Executor-Function)      // returns "promiseObj"

Executor-Function

should take 'two functions' as parameters -

  1. resolve() - called when the asynchronous task completes and returns the 'result'
  2. reject() - called when task is failed, and returns 'reason of failure' which is typically a 'error object'
const promise1 = new Promise((resolve, reject) => {
    // do something asynchronous
    //
    // resolve(someValue)
    // or
    // reject('reson for error')
})

Example

const promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('foo')
    }, 300)
})

promise1.then((value) => {
    console.log(value);         // foo
})

console.log(promise1)           // [object Promise]

3. Promise Consumption

const promise1 = new Promise()

const res = promise1.then(res => res.json()).catch(err => console.log(err));
// .then()   step after result is received
// .catch()  way to process error, if error happened

// Chaining
const res = promise1
.then(value1 => modify1(value1))
.then(value2 => modify2(value2))
.then(value3 => modify3(value3))
.catch(err => console.log(err))

4. Making functions returns a Promise

To provide a function with promise-functionality, have it return a promise-object

function myAsyncFunction(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest() 
    xhr.open("GET", url) 
    xhr.onload = () => resolve(xhr.responseText) 
    xhr.onerror = () => reject(xhr.statusText) 
    xhr.send() 
  });
}

5. Async Functions

Async Functions are instances of the AsyncFunction constructor, and await keyword is permitted within them.

The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

try{ } catch(e){ } block is used to process fulfilled (try{}) and failed (catch(e){}) requests

// 1. function returning promise
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

// 2. Async function
async function asyncCall() {
  console.log('calling');
  try {
      const result = await resolveAfter2Seconds();
      console.log(result);      // fulfilled
  } catch(err) {
      console.log(err)          // rejected, or any other err
  }
}

asyncCall();      // expected output: "resolved"

Top comments (0)