We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
自从 ES6 诞生以来,异步编程的方法得到了很大的发展。从 Promise 到 ES7 提案中的 async/await。目前,它仍处于提案阶段,async 函数可以说是目前异步操作最好的解决方案,是对 Generator 函数的升级和改进。那么今天就来具体说说 async/await 函数。
Promise
async/await
async
Generator
async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回一个 Promise 对象,等到异步操作完成,再接着执行函数体内后面的语句。
function timeout(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } async function asyncPrint(value, ms) { await timeout(ms); console.log(value); } asyncPrint('hello world', 50);
方法一
function timeout(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } async function asyncPrint(value, ms) { await timeout(ms); return value } asyncPrint('hello world', 5000).then(result=> { console.log(result); }).catch(err=>{ console.log(err) })
方法二
function timeout(ms) { return new Promise(resolve => { setTimeout(resolve, ms); }); } async function asyncPrint(value, ms) { try{ await timeout(ms); console.log(value) }catch(err){ console.log(err) } await timeout(ms); return value } asyncPrint('hello world', 5000)
await 后面紧跟着的最好是一个耗时的操作或者是一个异步操作(当然非耗时的操作也可以的,但是就失去意义了) 如果 await 后面的异步操作出错,那么等同于 async 函数返回的 Promise 对象被 reject
async 函数的学习到这里就结束了,但是这并不意味着 async 的用法只有这些,我们在学习了基础以后,更要把它与其他的知识相结合起来,才能写出更可靠更优质的代码!
The text was updated successfully, but these errors were encountered:
No branches or pull requests
async/await 简介
async/await 用法
async 函数返回一个 Promise 对象,可以使用 then 方法添加回调函数。当函数执行的时候,一旦遇到 await 就会先返回一个 Promise 对象,等到异步操作完成,再接着执行函数体内后面的语句。
错误处理
方法一
方法二
async 函数的学习到这里就结束了,但是这并不意味着 async 的用法只有这些,我们在学习了基础以后,更要把它与其他的知识相结合起来,才能写出更可靠更优质的代码!
The text was updated successfully, but these errors were encountered: