async/await implicitly returns promise?

前端 未结 5 2030
离开以前
离开以前 2020-11-22 12:06

I read that async functions marked by the async keyword implicitly return a promise:

async function getVal(){
 return await doSomethingAync();
}         


        
5条回答
  •  无人共我
    2020-11-22 12:46

    Your question is: If I create an async function should it return a promise or not? Answer: just do whatever you want and Javascript will fix it for you.

    Suppose doSomethingAsync is a function that returns a promise. Then

    async function getVal(){
        return await doSomethingAsync();
    }
    

    is exactly the same as

    async function getVal(){
        return doSomethingAsync();
    }
    

    You probably are thinking "WTF, how can these be the same?" and you are right. The async will magically wrap a value with a Promise if necessary.

    Even stranger, the doSomethingAsync can be written to sometimes return a promise and sometimes NOT return a promise. Still both functions are exactly the same, because the await is also magic. It will unwrap a Promise if necessary but it will have no effect on things that are not Promises.

提交回复
热议问题