async function - await not waiting for promise

前端 未结 4 1219
生来不讨喜
生来不讨喜 2020-12-30 22:52

I\'m trying to learn async-await. In this code -

const myFun = () => {
    let state = false;

    setTimeout(() => {state = true}, 2000);

    return         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-30 23:41

    There is no point to async and await when this is the actual case:

    Promise.resolve(3).then(console.log); console.log(4);
    4
    3
    

    In other words, since the then() forks and runs slower than the subsequent statements (even for a resolved Promise) then we need to put the subsequent statements inside the then, like:

    Promise.resolve(3).then(_ => { console.log(_); console.log(4); });
    3
    4
    

    And since that is true then why bother to await. So Im yet to see why async and await even exist.

提交回复
热议问题