Blue Flower

What is Promise?

JS executes its commands in a sequence and whenever it encounters a I/O bounded statement then it push it into event loop then continue its sequence and complete it.

During this execution cycle as and when it get breathing space it lookup event cycle (its a queue) and execute the completed I/O bound statements there. 

This is how it manages I/O request in asynchronous way.

Now we have a requirement to pause the execution, get result and then continue.  In order to handle this "promise" get into picture.  "async/wait" is the  syntactic sugar of "promise"

 

We can write promise in following simple ways

var gettickets = new Promise(function (resolve, reject){
setTimeout(()=> {resolve('ticket 3')},3000)
});


gettickets.then((res) => {
console.log('person 3 {res}');
})


or

 

function gettickets()
{
return new Promise(function (resolve, reject){
setTimeout(()=> {resolve('ticket 3')},3000)
});
}

gettickets().then((res) => {
console.log('person 3 {res}');
})

 

Comparision between Async/await & Promise

  • Is syntactic sugar syntax of Promise
  • Can place debug point in async/await statement

Example 1:

const makeRequest = () => {
return callAPromise()
.then( ()=> callAPromise())
.then( ()=> callAPromise())
.then( ()=> callAPromise())
.then( ()=> callAPromise())
}


const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
}

Example 2:

function fetchData(url) {
return fetch(url)
.then(response => response.text())
.then(text => {
console.log(text);
}).catch(err => {
console.error('error while fetching', err);
});
}


async function fetchData(url) {
try {
const response = await fetch(url);
console.log(await response.text());
}
catch (err) {
console.log('error while fetching', err);
}
}

 

Complete example to understand how the promise & async/await works

        console.log('Getup early morning');

console.log('brush up');

const getReadyForOffice = async () => {            

console.log('Have coffee'); //it get executed immediately       

function momPreparesSweet() {

                 return new Promise(function (resolve, reject) {

                    setTimeout(() => { resolve('sweet ready') }, 3000)

                });

            }

            

            console.log('read newspaper'); //it get executed immediately

            

            function hubbyPreparesDinner() {

                return new Promise(function (resolve, reject) {

                    setTimeout(() => { resolve('dinner ready') }, 3000);

                })

            }

            let sweet= await momPreparesSweet(); //pushed to event loop

            

            let dinner = await hubbyPreparesDinner(); //pushed to event loop

            

                        

            let [sweetReady,dinnerReady]=await Promise.all([sweet,dinner]); //wait for all promise to resolve/reject and collect its outcome

            console.log('do not wait for sweet as it will ready by evening'); //it get executed immediately

            console.log(`${sweetReady}... ${dinnerReady}`);

            return 'completes end of the day happily';

        }

        getReadyForOffice().then( (res)=>{console.log(`res:${res}`)});

        

        /**** OLD SYNTAX WIHOUT ASYNC/WAIT ******

             momPreparesSweet().then((res) => {

                 console.log(`${res} 3`);

             hubbyPreparesDinner().then( (res) => {console.log(res)});

                })

        

        ******************************************/

        console.log('take bike');

        console.log('goto office');

        setTimeout(() => { console.log('its time to goto bed after long work') }, 10000);

        console.log('start work');
 
Output Order
 
Getup early morning
brush up
Have coffee
read newspaper
take bike
goto office
start work
do not wait for sweet as it will ready by evening
sweet ready... dinner ready
completes end of the day happily
its time to goto bed after long work
 

You have no rights to post comments