generator函数 yield next()
可以控制代码执行的暂停与恢复,但不改变执行顺序
//generator函数 yield next()
//可以控制代码执行的暂停与恢复,但不改变执行顺序
function timer(n) {
setTimeout(function () {
console.log(n,n,n)
}, n)
}
function* test(){
yield timer(3000);
yield console.log(1111);
yield console.log(2222);
yield timer(5000);
console.log(3333);
};
var t = test();
t.next();
t.next();
t.next();
t.next();
t.next();
// 输出顺序
// 1111
// 2222
// 3333
// 3000 不到3秒 (从第一次执行next就开始计时)
// 5000 2秒 (从第一次执行next就开始计时)
async await
基于generator函数的语法糖,await后面必然是一个promise对象,await可以等待异步函数执行完毕再继续执行后面的代码,可以控制代码的执行顺序
//async await
//基于generator函数的语法糖,await后面必然是一个promise对象,await可以等待异步函数执行完毕再继续执行后面的代码,可以控制代码的执行顺序
async function f() {
let promise1 = new Promise((resolve, reject) => {
setTimeout(() => resolve('done!'), 5000)
})
let result1 = await promise1 // 直到promise返回一个resolve值(*)
console.log("111")
console.log(result1) // 'done!'
let promise2 = new Promise((resolve, reject) => {
setTimeout(()=>resolve('lalala'),5000)
})
console.log("222")
let result2=await promise2;
console.log(result2);
console.log("333")
};
f();
// 输出顺序
// 111 5秒后
// done!
// 222
// lalala 5秒后
// 333
参考 async/await:https://segmentfault.com/a/1190000013292562?utm_source=channel-newest
网友评论