-1

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

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Vivek Y V
  • 3
  • 2
  • 1
    You do not need to return a resolve(). You can just `resolve()` and not return anything. – Rojo Apr 09 '23 at 14:00
  • 1
    And I would recommend you [`push()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push) your elements into your array – Rojo Apr 09 '23 at 14:01
  • 3
    Sometimes you'll *need* to wrap a promise around a callback to be able to use it with async / await. Your function with `setTimeout` is a good example where there is no way around it. – Emiel Zuurbier Apr 09 '23 at 14:01

1 Answers1

1

The problem in the first snippet is in the add3 function

const add3 = async () =>  {
    setTimeout(() => {
        x = [...x, 3]
        return Promise.resolve()
    }, 4000)
}

In the above, return Promise.resolve() will be the return statement of the anonymous function passed to setTimeout but you're expecting it to be the return of the add3 async function. So return Promise.resolve() is not used anywhere.

const add3 = (z) => new Promise((resolve, reject) => {
    setTimeout(() => {
        x = [...x, 3]
        console.log(z)
        return resolve()
    }, 4000)
})

The second snippet works because even though return resolve() is the return of the inner arrow function, resolve param belongs to the wrapping promise so it resolves the same.

Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32