前端面试时被问到JS异步执行的问题:有A、B、C三个任务,要求:A和B异步执行,二者都完成后执行C

前端面试时被问到JS异步执行的问题:有A、B、C三个任务,要求:A和B异步执行,二者都完成后执行C

阅读 5.7k
7 个回答

方案一,Promise.all形式:

var promise1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log(1);
        resolve()
    }, 0);
    
});
var promise2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log(2);
        resolve()
    }, 0);
});
Promise.all([promise1, promise2]).then(function(res) {
  console.log(3)
});

方案二,callback形式:

var index = 0

function C(){
    console.log(3);
}

setTimeout(() => {
    console.log(1);
    index++;
    if(index === 2){
        C()
    }
}, 0);

setTimeout(() => {
    console.log(2);
    index++;
    if(index === 2){
        C()
    }
}, 0);
var a = Promise.resolve('a')

var b = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('b')
  }, 1000)
})

var c = function() {
  console.log('c')
}

Promise.all([a, b]).then(res => {
  res.forEach(console.log)
  c()
})
const A = async () =>  await 'A';
const B = async () =>  await 'B';
const C = () =>  'C';
(async function All() {
    await Promise.all([A(), B()]);
    C();
})();
async function A(){}

async function B(){}

function C(){}

Promise.all([A(),B()]).then(C)

给定一个计数器为2,A,B任务完成后,把计数器减去1,如果为0,则去指定C

可以用promise all

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题