定时器实现Promise.all()的简单使用
// 异步事件1 function time1() { const promise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("timer1执行完毕") }, 1000) }) return promise } // 异步事件2 function time2() { const promise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("timer2执行完毕") }, 2000) }) return promise } // 异步事件3 function time3() { const promise = new Promise(function (resolve, reject) { setTimeout(function () { resolve("timer3执行完毕") }, 3000) }) return promise } console.log("程序开始执行,计时开始....") console.time('程序运行耗时为') let t1 = time1() let t2 = time2() let t3 = time3() Promise.all([t1, t2, t3]).then(datas => { console.log(datas[0]) console.log(datas[1]) console.log(datas[2]) console.log(`全部执行完毕`) console.timeEnd('程序运行耗时为') })
效果图: