Async functions always return a promise
Example 1:
async function customAsyncFn() { //Inside an async function, use the await keyword before a call to a function //that returns a promise. const val = await new Promise(resolve => { setTimeout(() => { console.log("called setTimeout"); let users = [{ name: "raj", age: 24 },{ name: "mohan", age: 27 }] resolve(users); }, Math.random() * 1000); }); return val; } const cfn = customAsyncFn(); console.log(cfn); //expecting: Promise { <pending> } console.log(cfn[0].name); //expecting: error //as retun of async is PromiseOutput 1:
Promise { <pending> }
index.js:22
console.log(cfn[0].name); //expecting: error
^
TypeError: Cannot read properties of undefined (reading 'name')
index.js:22
console.log(cfn[0].name); //expecting: error
^
TypeError: Cannot read properties of undefined (reading 'name')
Try it
async function customAsyncFn() { //Inside an async function, use the await keyword before a call to a function //that returns a promise. const val = await new Promise(resolve => { setTimeout(() => { console.log("called setTimeout"); let users = [{ name: "raj", age: 24 },{ name: "mohan", age: 27 }] resolve(users); }, Math.random() * 1000); }); return val; } const cfn = customAsyncFn(); console.log(cfn); //expecting: Promise { <pending> } cfn.then((resolve) => { console.log(resolve[0].name); //expecting: raj });Output:
Promise { <pending> }
called setTimeout
raj
called setTimeout
raj