Why I can't access object properties with a .
in async await return object?
I know that I can access the properties like below.
let val1 = await call(3);
let val2 = await call(4);
but I'm interested if this can be done
let v = await call(3).val + await call(4).val;
const call = (x) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
val: x
});
}, 3000)
})
}
const dummy = async () => {
//let val1 = await call(3);
//let val2 = await call(4);
//alert(value.val + val2.val);
let v = await call(3).val + await call(4).val;
alert(v);
}
dummy()
Using return await inside an async function keeps the current function in the call stack until the Promise that is being awaited has resolved, at the cost of an extra microtask before resolving the outer Promise.
Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.
The await keyword is used in an async function to ensure that all promises returned in the async function are synchronized, ie. they wait for each other. Await eliminates the use of callbacks in .
await only blocks the execution of the next lines of code in an async function and doesn't affect the promise execution.
If you want to run this with await, you will have to use it inside an async function Show activity on this post. You can simply put the async keyword on any function, not only function declarations but also function expressions and methods of object. For example:
Starting with C# 7.0, an async method can return any type that has an accessible GetAwaiter method that returns an instance of an awaiter type. In addition, the type returned from the GetAwaiter method must have the System.Runtime.CompilerServices.AsyncMethodBuilderAttribute attribute.
The word “async” before a function means one simple thing: a function always returns a promise. If the code has return <non-promise> in it, then JavaScript automatically wraps it into a resolved promise with that value.
Let’s start with the async keyword. It can be placed before a function, like this: The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
You're trying to await the value of the val
property of the promise.
You need to await the promise and then read the val
property from the result: (await call(3)).val
const call = (x) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
val: x
});
}, 3000)
})
}
const dummy = async () => {
let v = (await call(3)).val + (await call(4)).val;
alert(v);
}
dummy()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With