Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

async/await #44

Open
sfsoul opened this issue Dec 17, 2019 · 0 comments
Open

async/await #44

sfsoul opened this issue Dec 17, 2019 · 0 comments

Comments

@sfsoul
Copy link
Owner

sfsoul commented Dec 17, 2019

async函数的返回值

async关键字做了什么:

  • 被 async 操作符修饰的函数必然返回一个 Promise;
  • 当 async 函数返回一个值时,Promise 的resolve方法负责传递这个值;
  • 当 async 函数抛出异常时,Promise 的reject方法会传递这个异常值。
async function fn() {
     return 'async111';
}
const p = fn();
console.log(p); // Promise {<resolved>: "async111"}  (返回一个状态为resolved,值为async111的Promise实例)

// 等价于
function fn1(){
    return Promise.resolve('async111');    
}
const p1 = fn1();
console.log(p1); // Promise {<resolved>: "async111"} 

await操作符做了什么

简单总结一下对于 await v

  • await 后的值 v 会被转换为 Promise
  • 即使 v 是一个已经 fulfilled 的Promise,还是会新建一个Promise,并在这个新Promise中resolved(v)
  • await v 后续的代码的执行类似于传入 then()的回调。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant