--async and await is used to consume promises , not to produce them .
--async and await makes easier to consume promise over then and catch .
--await can only be used inside async function.
--an async function is always returns a promise automatically.
Example:
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);
});
};
//Consuming promises
//Async & await
async function getReceipeAW() { //here async is the keyword
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);
}
getReceipeAW();
No comments:
Post a Comment