1

const testAsync = function (name) {
  return new Promise((resolve, reject) => {
       console.log(name)
       resolve(name);
  })
}

async function asynFunc () {
    let result = ''
    result += await testAsync('a')
    result += await testAsync('b')
    result += await testAsync('c')
}

function test(){
    console.log('start')
    asynFunc();
    console.log('end')
}


test()

the output is:

> "start"
> "a"
> "end"
> "b"
> "c"

but what I'm expecting is

> "start"
> "a"
> "b"
> "c"
> "end"

What cause the result to be Out-of-Sequence? What's more, I was expecting the program to end when it prints 'end', but apparently not.

choxsword
  • 3,187
  • 18
  • 44
  • 1
    Because `asynFunc()` is `async`, so you need an `await` in `test()`. – double-beep Jan 02 '21 at 14:53
  • 1
    You're not awaiting `asyncFunc` – Christian Jan 02 '21 at 14:53
  • @double-beep I was not asking for the right solution, but for a explaination for why it happens like that. – choxsword Jan 02 '21 at 14:56
  • @Christian yes every tutorial will say `async` is needed here. But why it happends like this when no `async` is specified? – choxsword Jan 02 '21 at 14:59
  • Even when a Promise is resolved immediately, the execution of subsequent `.then()` callbacks (which is how the second two `await` expressions work, basically) are performed in a special context asynchronously. – Pointy Jan 02 '21 at 15:04

0 Answers0