鍍金池/ 問答/Linux  HTML/ 前端面試時被問到JS異步執(zhí)行的問題:有A、B、C三個任務(wù),要求:A和B異步執(zhí)行,

前端面試時被問到JS異步執(zhí)行的問題:有A、B、C三個任務(wù),要求:A和B異步執(zhí)行,二者都完成后執(zhí)行C

前端面試時被問到JS異步執(zhí)行的問題:有A、B、C三個任務(wù),要求:A和B異步執(zhí)行,二者都完成后執(zhí)行C

回答
編輯回答
青裙

clipboard.png

可以使用 promise.all,原文地址:https://github.com/chenyinkai...

2017年5月12日 00:42
編輯回答
心夠野

可以用promise all

2017年10月24日 18:25
編輯回答
葬憶

方案一,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);
2018年7月12日 20:29
編輯回答
耍太極

給定一個計數(shù)器為2,A,B任務(wù)完成后,把計數(shù)器減去1,如果為0,則去指定C

2017年4月23日 14:50
編輯回答
傲嬌范
async function A(){}

async function B(){}

function C(){}

Promise.all([A(),B()]).then(C)
2017年7月9日 00:51
編輯回答
陌顏
const A = async () =>  await 'A';
const B = async () =>  await 'B';
const C = () =>  'C';
(async function All() {
    await Promise.all([A(), B()]);
    C();
})();
2017年9月15日 02:47
編輯回答
青瓷
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()
})
2017年8月23日 00:02