I'm doing a little thought experiment about async/await with non-thenable values. Here, I have some code. I'm having trouble understanding why the output is 1 and then 2. Is it because when I invoke my asynchronous function increment()
, the functionality inside gets wrapped in a Promise
? I think I might get a better understanding if I could write this as without async/await and with Promises instead, but I'm not sure where to start.
let num = 0;
async function increment() {
num += await 2;
console.log(num);
}
increment();
num+=1;
console.log(num);
//1
//2
According to MDN, async
functions return a Promise
that is resolved to the value returned by the async
function. Expressions in front of await
that are not thenables are wrapped inside of a Promise.resolve
and subsequent code gets wrapped in a then()
. By looking at my exercise, I see that my async
function does not feature a hard coded return
but it does have an await
. Since the await
is followed by a non-thenable, I believe it should wrap that expression in a Promise.resolve
, so it would be Promise.resolve(2)
. I thought my code block below would work at first but clearly the fulfilled value of the promise does not get added the way I want it to.
let num = 0;
function increment() {
num += Promise.resolve(2).then((value) => value).then((value) => console.log(value));
}
increment();
num+=1;
console.log(num);