node.js - Promise inside loop in nodejs isn't working as expected -
i have array of events, each value there may/may not query fires data.
var eventtypes = [["write","write","write","write"],["write","write","read","write"]]; _.each(eventtypes,function(obj){ gettime(obj); }); gettime=function(events){ var resultarray = []; _.each(events,function(event){ if(event === "read"){ resultarray.push(makesqlquery(event)); }else{ resultarray.push({"time":current_time}) } }); q.all(resultarray).then(function(finalresult){ insertintopostgresql(finalresult); }); } makesqlquery = function(event){ var deferred = q.defer(); sql.query("select time events eventtype ="+ event, function(result,error){ if(error){ deferred.reject(error); }else{ deferred.resolve({time:result.time}); } }); return deferred.promise; }
in above code i'm able push 1st set of data(["write","write","write","write"]
) postgresql
database not 2nd set(["write","write","read","write"]). whenever read
event in set, i'm getting empty object. problem? above example should have 8 records in postgresql
, see first array's 4 data.
more info: insertintopostgresql()
function list of objects , insert each object database. operation workin fine.
i tried use 2 console stmt
console.log("sql result:"result); deferred.resolve({time:result.time});
and
console.log("before insert:"json.stringigy(resultarray)); q.all(resultarray).then(function(finalresult){
i result in following order.
before insert:[{"source":{}},{"source":{}},{"source":{}},{"source":{}}]
before insert:[{}]
sql result:{time:"2015-07-10 00:00:00"}
as roamer-1888 mentioned in comments, add error handler q.all
. basic structure of promise seems fine, error somewhere else.
it looks result
in sql.query
callback not quite expect, read undefined
. because of error there, q.all not getting resolved, therefore nothing gets added database.
Comments
Post a Comment