I know a few things about async/ await is that only async functions can use await, await waits for a promise/async-function to return a resolve or reject. I was hence trying to learn it in depth but got confused as why this code wasnt giving expected results
var x = [1]
const add2 = async () => {
x = [...x, 2]
return Promise.resolve()
}
const add3 = async () => {
setTimeout(() => {
x = [...x, 3]
return Promise.resolve()
}, 4000)
}
const final = async () => {
console.log(x)
await add2()
console.log(x)
await add3()
console.log(x)
}
final()
This would give me output as
[1]
[1, 2]
[1, 2]
Whereas my expected output was
[1]
[1, 2]
[1, 2, 3]
So i tried to make a few changes and i got the output
var x = [1]
const add2 = async () => {
x = [...x, 2]
return Promise.resolve()
}
const add3 = (z) => new Promise((resolve, reject) => {
setTimeout(() => {
x = [...x, 3]
console.log(z)
return resolve()
}, 4000)
})
const final = async () => {
console.log(x)
await add2()
console.log(x)
await add3()
console.log(x)
}
final()
So i am confusion wether i can implement this functionality using just async function and not defining a new promise