let say there is one method fetchData which have one promise.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
let data = { pCode: "10001", pName: "orange" };
resolve(data);
}, 2000);
});
}
console.log("program start here");
fetchData().then((res) =>{
console.log(res)
}).catch((err) =>{
console.log(err)
}).finally(()=>{
console.log("program ends here")
})
console.log("all done!!")
actual output as below. Here last console "All Done!!" get executed before "program ends here" -:
program start here
all done!!
{ pCode: '10001', pName: 'orange' }
program ends here
So question is, can we wait till fetchData function done all its taks then print last log "all done !!", something like -:
program start here
{ pCode: '10001', pName: 'orange' }
program ends here
all done!!
why I am expecting this because when I call
const obj= {
a: fetchData()
}
console.log(obj)
it prints { a: Promise { } }
and I need something like
{ a:{ pCode: '10001', pName: 'orange' }
I tried below option but non of them working
1.
const obj={
a: (async() => await fetchData())() // cannot use await without async
}
console.log(obj)
output :
{ a: Promise { <pending> } }
const obj={
a: fetchData().then((res)=>{
return res;
})
}
output :
{ a: Promise { <pending> } }