There seems to be an issue in your code where you are assigning the result of a
(which is an asynchronous function, thus returning a Promise
) to newObj.a
An asynchronous function can include an await expression that halts the execution of the asynchronous function until the Promise it awaits resolves, and then continues with the function's execution, returning the resolved value. For more details, you can refer to this link: here
Keep in mind that the await keyword is only valid within async functions. If used outside of an async function body, it will lead to 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: Upon johnson andriatiana's request, I have enclosed the code within an 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)
})();