async function f1() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('5000ms passed');
resolve()
}, 5000)
})
}
async function f2() {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log('1000ms passed');
resolve()
}, 1000)
})
}
async function test() {
// 使f1,f2并发异步执行
const r1 = f1()
const r2 = f2()
console.log(await r1);
console.log(await r2)
// 同步
const r1 = await f1()
const r2 = await f2()
console.log(r1);
console.log(r2);
}
test()
或者:
使用 Promise.all
const [r1,r2] = await Promise.all([fn1,fn2])
来进行并发执行,获取到结果后进行处理