async包 ES6 async/await的区别
最基本的async 包
ApCollection.find({}).toArray(function (err, aps) { var num = 0; async.whilst( function () { return num++ < aps.length; }, function (callback) { if (aps[num]) { var apmac = aps[num].AP_MAC; ApHeartCollection.findOne({ AP_MAC: apmac, time: { $gte: nowtime } }, function (err, log) { ApCollection.update({ _id: aps[num]._id }, { $set: { c: 2 } }, function (err, doc) { callback(); }) }) } else { callback(); } }, function (err) { console.log('finish server status update'); }) })
用 async/await+promise
async function changeApServerStatus() { var nowtime = new Date().getTime() / 1000; var pro = tool.GetDB(); await pro; await pro.then(function(args: any) { return new Promise(function(resovle, reject) { args.db.collection('ap').distinct('mac', function(err, macs) { if (!err) { args.macs = macs; resovle(args); } reject(err); }) }) }).then(function(args: any) { var macs: Array<string> = args.macs var num = 0; var ApCol = args.db.collection('ap') return myasync.whilst( function() { return num < macs.length; }, function() { return new Promise(function(resovle, reject) { ApCol.findOne({ mac: macs[num] }, function(err, ap) { num++; if (!err) { resovle(ap); } reject(err); }) }).then(function(ap: any) { console.log(num) if (ap.datastatus == 0) { console.log("is 0") return new Promise(function(resovle, reject) { ApCol.update({ mac: ap.mac }, { $set: { c: 2 } }, function(err, doc) { console.log("update " + doc); resovle(doc) }) }) } console.log("is 1") }) } ) }) }
换种方式 只是迭代里换了
async function changeApServerStatus() { var nowtime = new Date().getTime() / 1000; var pro = tool.GetDB(); await pro; await pro.then(function(args: any) { return new Promise(function(resovle, reject) { args.db.collection('ap').distinct('mac', function(err, macs) { if (!err) { args.macs = macs; resovle(args); } reject(err); }) }) }).then(function(args: any) { var macs: Array<string> = args.macs var num = 0; var ApCol = args.db.collection('ap') async function iter(mac) { var pap await new Promise(function(resolve, reject) { ApCol.findOne({ mac: mac }, function(err, ap) { num++; if (!err) { pap = ap resolve(ap) } reject(err) }) }) await (function() { console.log(num+" "+mac) if (pap.datastatus == 0) { console.log("is 0") return new Promise(function(resolve, reject) { ApCol.update({ mac: pap.mac }, { $set: { c: 2 } }, function(err, doc) { console.log("update " + doc); resolve(doc) }) }) } console.log("is 1") })() } return myasync.whilst( function() { return num < macs.length; }, function() { return iter(macs[num]) } ) }) }
async/await迭代器实现
var whilst = async function(test, callback) { while (test()) { await callback(); } return "end" };
async的迭代器
function whilst(fntest, fniterator, fnend) { if (fntest()) { fniterator(function (err) { if (err) { fnend(err) } whilst(fntest, fniterator, fnend) }) } else { fnend() } }