看不少教程,也一直在用,就是云里雾里的。闲下来自己跑着玩,终于清爽很多。
- async 和 await 都一个修饰符,都是获取返回的 promise 内容。
- async 修饰的函数会返回一个 promise 对象
- await 放在调用返回值为 promise 对象的函数前使用
- await 关键字仅在 async 函数中有效。如果在 async 函数体外使用 await ,你只会得到一个语法错误。
- 如果在循环中使用 await 语句,就要使用 for 循环,其它的如 each 中不起作用
- async 函数执行时,如果遇到 await 就会先暂停执行 ,等到触发的异步操作完成后,恢复 async 函数的执行并返回解析值。
const asy = function(x, time) {
return new Promise((resolve, reject) =>{
setTimeout(()=>{
resolve(x)
}, time)
})
}
const add = async function() {
let result = {}
let a = await asy("1秒", 1000)
console.log(a)
let b = await asy("3秒", 3000)
console.log(b)
let c = asy("10秒", 10000)
console.log(c)
console.log(a,b,c)
let d = a + b + c
console.log(d)
c.then(res=>{
console.log(res)
result.c_result = a+b+res
console.log(result)
})
console.log(a+b+c)
result.add_result='add 完成'
return result
}
add().then(res=>{
console.log('调用 add 1')
console.log(res)
console.log('调用 add 2')
});
> 1秒
> 3秒
> {}
> 1秒,3秒,{}
> 1秒3秒[object Promise]
> 1秒3秒[object Promise]
> 调用 add 1
> {"add_result":"add 完成"}
> 调用 add 2
> 10秒
> {"add_result":"add 完成","c_result":"1秒3秒10秒"}
自己跑一下,整个人都好了…