let wake = (time) => { let now = new Date().getSeconds() return new Promise((resolve, reject) => { setTimeout(() => { resolve(`当前时间 ${now}, 以后时间 ${new Date().getSeconds()}, ${time / 1000}秒后醒来`) }, time) }) } let p1 = wake(3000) let p2 = wake(2000) Promise.all([p1, p2]).then((result) => { console.log(result) // [ '3秒后醒来', '2秒后醒来' ] console.log('--------', new Date().getSeconds()) }).catch((error) => { console.log(error) })
结果:
[ '当前时间 39, 以后时间 42, 3秒后醒来', '当前时间 39, 以后时间 41, 2秒后醒来']
-------- 42
拓展:
Promise.race用法相似用Promise.all,区别于Promise.all里面的方法是同时执行且等到全部异步方法执行完了才会回调;Promise.race则是里面方法先执行结束,就返回那个结果,且无论结果自己是成功状态仍是失败状态异步
参考:https://www.jianshu.com/p/7e6...async
并行 async.parallel方法能够解决
拓展:async的其余方法
串行 无关联 async.series
串行 有关联 async.waterfallcode
自动 async.autoget
let arr = [1000, 2000, 3000] let newArr = [] async.forEach(arr, (value, done) => { let now = new Date().getSeconds() setTimeout(function () { newArr.push(value) console.log('当前时间:', now, '结束时间:', new Date().getSeconds()) done() }, value) // timeOut(value) }, err => { if (err) console.error(err.message) console.log(newArr) console.log('最终时间', new Date().getSeconds()) }) console.log('最终时间2', new Date().getSeconds())
结果:
最终时间2 18
当前时间: 18 结束时间: 19
当前时间: 18 结束时间: 20
当前时间: 18 结束时间: 21
[ 1000, 2000, 3000 ]
最终时间 21it