node.js - Iterating with Q -
i have collection in mongodb (i'm omitting _id
s brevity):
test> db.entries.find(); { "val": 1 } { "val": 2 } { "val": 3 } { "val": 4 } { "val": 5 }
i need perform processing on each document cannot db.update()
. so, in nutshell, need retrieving 1 document @ time, process in node , save mongo.
i'm using monk library, , q promises. here's i've done — didn't include processing/save bit brevity:
var q = require('q'); var db = require('monk')('localhost/test'); var entries = db.get('entries'); var = 1; var total; var f = function (entry) { console.log('i = ' + i); console.log(entry.val); i++; if (i <= total) { var promise = entries.findone({ val: }); loop.then(function (p) { return f(p); }); return promise; } }; var loop = q.fcall(function () { return entries.count({}); }).then(function (r) { total = r; return entries.findone({ val: }); }).then(f);
i expect code print out:
i = 1 1 = 2 2 = 3 3 = 4 4 = 5 5
but prints out:
i = 1 1 = 2 2 = 3 2 = 4 2 = 5 2
what doing wrong?
in code, loop 1 , 1 promise. executed once. not function. inside f
, loop.then(f)
trigger f
result of promise (it has been executed not executed again).
you want create several promises. looking should looks like:
var q = require('q'); var db = require('monk')('localhost/test'); var entries = db.get('entries'); var = 1; var total; var f = function (entry) { console.log('i = ' + i); console.log(entry.val); i++; if (i <= total) { // not sure why put entries.findone here (looks mistake, // returned value isn't used) if need done // before loop, must pipe before loop return entries.findone({ val: }).then(loop); // not pipe f again here, appended @ end of loop } }; function loop(){ return q.fcall(function () { return entries.count({}); }).then(function (r) { total = r; return entries.findone({ val: }); }).then(f); } loop();
if interested, here nice article promises.
Comments
Post a Comment