Async await strange behaviour with functions

前端 未结 2 2031
隐瞒了意图╮
隐瞒了意图╮ 2020-12-21 22:16

I have following asynchronous code example:

// Functions

function getSomePromise() {
    let a = new Promise((resolve, reject) => {    
        setTimeou         


        
2条回答
  •  北海茫月
    2020-12-21 23:04

    Looking at the comments

    @HMR - hm... I not understand - in question example there is async function someWrapper() but that function don't return anything (it even doesn't have return statement (!) ) - can you explain what do you mean by async functions immediately return a promise? - Kamil Kielczewski

    it seems you don't understand the async await. I usually advice people to lay off await until you understand promises. However in next comment under question I give you the answer:

    someWrapper will immediately return a promise that resolves to undefined. The await only "waits" in the someWrapper function but the function calling someWrapper will immediately receive a promise that resolves in undefined. Functions always return something, if you don't in code then it will return undefined. If it's an async function without a return then it'll return a promise that resolves in undefined - HMR.

    Await is syntax sugar (nicer looking code) for promises and doesn't actually wait for anything.

    Maybe the following code clears things up:

    var test = async () => {
       await 22;//doesn't even matter if value is promise
       console.log("after wait");
    }
    var result = test();
    console.log("outside test we don't wait for anything",result);

    If you don't understand why the output of that code is:

    outside test we don't wait for anything Promise {< pending >}

    after wait

    Then I'd advice you to use just promises, until you do.

提交回复
热议问题