- 两个函数并行执行最简作法
const fun1 = () => {
setTimeout(()=>{// 方便测函数的执行顺序
console.log("fun1")
}, 1000)
}
const fun2 = () => {
setTimeout(()=>{
console.log("fun2")
}, 100)
}
setTimeout(fun1)
setTimeout(fun2)
依次打印 fun2 fun1
在函数内部写计时器是为了便于测函数的执行顺序
- 两个函数并行执行后再去执行其他操作
Promise
const fun1 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('f1')
resolve("1")
}, 1000)
})
const fun2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log('f2')
reject('2')
}, 800)
})
Promise.all([fun1, fun2]).then(values => {
console.log('resolve', values)
}, values=>{
console.log('reject', values)
})
// 打印顺序依次是f2, reject 2, f1
有一个函数返回了reject, 则 then 的第二个函数会被调用,
仅当两个函数都 resolve 时,then 的第一个函数会被调用,values代表状态下的参数
var p = Promise.all([1,2,3]);
var p2 = Promise.all([1,2,3, Promise.resolve(444)]);
var p3 = Promise.all([1,2,3, Promise.reject(555)]);
setTimeout(function(){
console.log(p);
console.log(p2);
console.log(p3);
});
// 结果
Promise { [ 1, 2, 3 ] }
Promise { [ 1, 2, 3, 444 ] }
Promise { <rejected> 555 }
// 若去掉setTimeout
Promise { <pending> }
Promise { <pending> }
Promise { <pending> }
在setTimeout 内部执行的是异步代码,可以等到函数准备好后,再获取执行环境。
Generator
const fun1 = () => {
console.log('fun1')
return '1'
}
const fun2 = () => {
console.log('fun2')
return '2'
}
function* gen(fun1, fun2, fun3) {
yield fun1()
yield fun2()
return 'done!'
}
const g = gen(fun1, fun2)
console.log(g.next()) // fun1 { value: '1', done: false }
接着再执行
console.log(g.next()) // fun2 { value: '2', done: false }
若同时打印,则f1, f2均异步,完成顺序因函数本身而定
async
const fun1 = () => {
console.log('fun1')
return 1
}
const fun2 = () => {
console.log('fun2')
return 2
}
async function handle(fun1, fun2) {
const a = await fun1()
const b = await fun2()
console.log(a + b)
return a
}
handle(fun1, fun2).then(value => {
console.log(value)
})
打印顺序:fun1 fun2 3 1
捕获错误
const fun1 = () => {
return new Promise((resolve, reject)=>{
reject("error")
})
// throw 'oh, no'
}
const fun2 = () => {
console.log('fun2')
return 2
}
async function handle(fun1, fun2) {
const a = await fun1()
.catch(err => {
console.log("a",err)
})
const b = await fun2()
console.log(a, b)
return "done"
}
handle(fun1, fun2).then(
value => {
console.log('resolve', value)
},
value => {
console.log('reject', value)
}
)
// 打印顺序:
a error
fun2
undefined 2
resolve done
若将a 对应函数后的catch 去掉, 则打印
reject error
错误经捕获后,执行 then 参数中第一个回调函数