异步操做是 JavaScript 编程的麻烦事,麻烦到一直有人提出各类各样的方案,试图解决这个问题。从最先的回调函数,到 Promise 对象,再到 Generator 函数,每次都有所改进,但又让人以为不完全。它们都有额外的复杂性,都须要理解抽象的底层运行机制。异步I/O不就是读取一个文件吗,干吗要搞得这么复杂?异步编程的最高境界,就是根本不用关心它是否是异步。async 函数就是隧道尽头的亮光,不少人认为它是异步操做的终极解决方案。--阮老师的博客
async 表示这是一个async函数,await只能用在这个函数里面。编程
await 表示在这里等待promise返回结果了,再继续执行。promise
await 后面跟着的应该是一个promise对象(固然,其余返回值也不要紧,只是会当即执行,不过那样就没有意义了…)异步
function waitAMinute(time) {
return new Promise(resolve=>{
setTimeout(()=>{
resolve(20)
}, time)
})async
async function test() {
console.log('hello world')
console.log(await waitAMinute(2000)) //两秒钟后输出20
console.log('welcome')
}异步编程
test(); //hello world , 20, welcome函数
let start = function() {
return new Promise(resolve=>{
setTimeout(()=>{
resolve('HelloWorld')
})
})
}code
let end = async function() {
let result = await start()
console.log(result) //获取结果HelloWorld
}
end()对象
既然then没必要写了,那么.catch()也不须要写了,直接将await代码放入try/catch异常处理块儿当中ip
let end = async function() {
try {
let result = await start()
console.log(result)
} catch(error) {
throw new Error(err.message)
}
}回调函数
[...].forEach(function(value,index){ console.log('当前是第'+ index +'次调用') var result = await start() //报错 })