标签:
最基本的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/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() } }
标签:
原文地址:http://www.cnblogs.com/zihunqingxin/p/4964941.html