ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## async-await 与其他方式对比 async / await 是 ES2017中引入的,为了使异步操作得更加方便,本质上 async 函数是 Generator 函数的语法糖。 async 函数书写的方式跟我们普通的函数书写方式一样,只不过是前面多了一个 async 关键字,并且函数返回的是一个 Promise 对象,所接收的值就是函数 return 的值。 在 async 函数内部可以使用 await 命令,表示等待一个异步函数的返回。await 后面跟着的是一个 Promise 对象,如果不是的话,系统会调用 Promise.resolve() 方法,将其转为一个 resolve 的 Promise 的对象。 假设有那么一个异步函数 : ``` function p (num) { if (num >= 0) { return Promise.resolve(num) } else { return Promise.reject(new Error('参数不能小于 0')) } } ``` ### 普通的 Promise 调用方式 : ``` console.log('-1-') p(1).then(data => { console.log(data) retrun p(2) }).then(data => { console.log(data) }) console.log('-2-') ``` 输出 ``` -1- -2- 1 2 ``` ### 使用 Generator 调用方式 ``` function *gen() { yield p(1) yield p(2) } let g = gen() console.log('-1-') g.next().value.then(data => { console.log(data) return g.next().value }).then(data => { console.log(data) return g.next().value }).then(console.log) console.log('-2-') ``` 输出 ``` -1- -2- 1 2 undefined ``` ### 使用 async-await 方式 : ``` async function ps() { let a = await p(1) console.log(a) let b = await p(2) console.log(b) return [a, b] } console.log('-1-') ps().then(res => { console.log(res) }) console.log('-2-') ``` 输出 ``` -1- -2- 1 2 [1, 2] ```