async/await implicitly returns promise?

前端 未结 5 2031
离开以前
离开以前 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:50

    I took a look at the spec and found the following information. The short version is that an async function desugars to a generator which yields Promises. So, yes, async functions return promises.

    According to the tc39 spec, the following is true:

    async function ?
    

    Desugars to:

    function ?{ return spawn(function*() , this); }
    

    Where spawn "is a call to the following algorithm":

    function spawn(genF, self) {
        return new Promise(function(resolve, reject) {
            var gen = genF.call(self);
            function step(nextF) {
                var next;
                try {
                    next = nextF();
                } catch(e) {
                    // finished with failure, reject the promise
                    reject(e);
                    return;
                }
                if(next.done) {
                    // finished with success, resolve the promise
                    resolve(next.value);
                    return;
                }
                // not finished, chain off the yielded promise and `step` again
                Promise.resolve(next.value).then(function(v) {
                    step(function() { return gen.next(v); });
                }, function(e) {
                    step(function() { return gen.throw(e); });
                });
            }
            step(function() { return gen.next(undefined); });
        });
    }
    

提交回复
热议问题