Tuesday, January 4, 2022

How to consume promise when returning a resolved value

 const ids = new Promise((resolve, reject) => { //promise 1

    setTimeout(() => {

        resolve([100, 200, 300, 400, 500]);

    }, 1500);

});

const getReceipe = recId => {  //promise 2

    return new Promise((resolve, reject) => {

        setTimeout(id => {

            const receipe = {

                title: 'potato',

                publisher: 'jonas'

            };

            resolve(`${id}:${receipe.title}`);

        }, 1500, recId);

    });

};


async function getReceipeAW() {

    const allIds = await ids; // here ids is the promise . await keyword is used to wait 

                                          //until the promise resolved

    console.log(allIds);

    const receipe = await getReceipe(allIds[2]);

    console.log(receipe);

    return receipe;

}

getReceipeAW().then(result=>{   // here getReceipeAW() will return a promise then

                                                      //  we need to consume it.

    console.log(`${result} is the best food ever`);

})

No comments:

Post a Comment

Fluent interface pattern

 public class UserConfigurationManager {     private String userName;     private String password;     private UserConfigurationManager() { ...