const async = require(‘async’)
console.time(‘async’)
// 串行无关联
// 数组里有很多个异步代码,第一个异步完成以后调用了cb才会执行第二个
// 当数组里的所有异步都完成(数组最后一个cb被调用了),这个时候最终的回调函数就会被执行
// 最后这个回调里可以在第二个参数是个数组,接收数组每一个cb传递过来的参数
// async.series([
// (cb) => {
// // 异步程序
// setTimeout(() => {
// console.log(1)
// // 调用cb的目的时告诉数组的第二个函数我这里异步结束了,你可以开始执行了
// cb(null, ‘one’)
// }, 2000)
// },
// (cb) => {
// setTimeout(() => {
// console.log(2)
// cb(null, ‘two’)
// }, 3000)
// }
// ], (err, res) => {
// // 这个函数在数组最后一个cb调用之后执行
// console.log(res)
// console.timeEnd(‘async’)
// })
// 串行有关联
// 串行,但是cb的参数是一次往下传递的
// cb参数传递的是什么,下一个函数里接受的就是什么
// async.waterfall([
// cb => {
// setTimeout(() => {
// console.log(‘one’)
// cb(null, ‘one’)
// }, 1000)
// },
// (str, cb) => {
// setTimeout(() => {
// console.log(str + ’ two’)
// cb(null, str + ’ two’)
// }, 2000)
// }
// ], (err, res) => {
// // res接受的是最后一个cb传递过来的参数
// console.log(res)
// })
// 并行无关联
async.parallel([
cb => {
setTimeout(() => {
console.log(1)
cb(null, ‘one’)
}, 4000)
},
cb => {
setTimeout(() => {
console.log(2)
cb(null, ‘two’)
}, 3000)
}
], (err, res) => {
console.log(res)
console.timeEnd(‘async’)
})