The problem with your code is you are assigning return of a
(which is an async function, so it will return a Promise
) to newObj.a
An async function can contain an await expression that pauses the execution of the async function and waits for the passed Promise's resolution, and then resumes the async function's execution and returns the resolved value. You can read more about it here
Remember, the await keyword is only valid inside async functions. If you use it outside of an async function's body, you will get a SyntaxError.
Approach 1
const promise1 = new Promise(function(resolve, reject) {
resolve('myvalue');
});
const a = async() => {
var b = await promise1
return b;
}
const printData = async() => {
const newobj = {
'a': await a()
};
console.log(newobj)
}
printData()
EDIT: As requested by johnson andriatiana, I have wrapped the code in async IIFE function.
Approach 2:
(async() => {
const promise1 = new Promise(function(resolve, reject) {
resolve('myvalue');
});
const a = async() => {
var b = await promise1
return b;
}
const newobj = {
'a': await a()
};
console.log(newobj)
})();