here I tried to get a value from the function in this case my function return an object, When i try to access it with key I get "undefined" as bar1 but bar2 It's has values of a object.
const foo = async()=> {
let zoo
let data = [
{
key1:"1",
key2:"a",
key3:3,
key4:"cal",
}
]
for (const iterator of data) {
// console.log(iterator)
bar1 = {
objectLiteral_swithAsync: await objectLiteral_swithAsync(iterator["key4"]).exe1,
objectLiterals_withOutAsync : objectLiterals_withOutAsync(iterator["key4"]).exe1,
switch_WithAsync : await switch_WithAsync(iterator["key4"]).exe1,
switch_WithOutAsync : switch_WithOutAsync(iterator["key4"]).exe1,
}
bar2 ={
objectLiteral_swithAsync: await objectLiteral_swithAsync(iterator["key4"]),
objectLiterals_withOutAsync : objectLiterals_withOutAsync(iterator["key4"]),
switch_WithAsync : await switch_WithAsync(iterator["key4"]),
switch_WithOutAsync : switch_WithOutAsync(iterator["key4"]),
}
zoo = {
bar1 :bar1,
bar2: bar2
}
}
return zoo
}
async function objectLiteral_swithAsync(param) {
let obj= {
'cal': 2 * 2
}[param]
let result = {
exe1 : obj,
exe2: 2
}
return result
}
function objectLiterals_withOutAsync(param) {
let obj= {
'cal': 2 * 2
}[param]
let result = {
exe1 : obj,
exe2: 2
}
return result
}
async function switch_WithAsync (param){
let obj
switch (param) {
case "cal":
obj = 2 * 2
break;
default:
obj =0
break;
}
result = {
exe1 : obj,
exe2: 2
}
return result
}
function switch_WithOutAsync (param){
let obj
switch (param) {
case "cal":
obj = 2 * 2
break;
default:
obj =0
break;
}
result = {
exe1 : obj,
exe2: 2
}
return result
}
foo().then( result=>{
console.log('--->1',result)
})
// console.log('2', foo())
the result in object bar1 are undefined when its called asyncfunction with the . notation but in bar2 every keys has a value.
Promises don't have a
.exe1property, yet your code is trying to retrieve such property from a promise object.In this expression:
...the order of evaluation is as follows:
iterator["key4"]evaluates to "cal"objectLiteral_swithAsync(iterator["key4"])evaluates to a promise (anasyncfunction returns a promise)<a promise>.exe1evaluates toundefinedas it accesses a non-existing propertyawait undefinedwill suspend the function to be resumed asynchronously, and then this evaluates toundefinedWhat you really want, is to have the
.exe1access to happen when you already have awaited the promise and have the value it fulfilled with. So change the order of execution with parentheses:Now the order of evaluation is as follows:
iterator["key4"]evaluates to "cal"objectLiteral_swithAsync(iterator["key4"])evaluates to a promise.await <promise>suspends the function until the promise is resolved. When it resumes asynchronously, this expression evaluates to{exe1: 4, exe2: 2}({exe1: 4, exe2: 2}).exe1evaluates to 4