javascript - How to process users in one specific order using map o each function? -
i create cloud function process items in specific order , make network request api each item , update them result of api.
i tried this. order not respected , computation of "remainingcredits" wrong. note function "getuserpageview()" make api call , return promise result.
query.descending("createdat"); return query.find().then(function(items) { var remainingcredits=0; var promises= _.map(items, function(item){ var credit=item.get("credit_buy"); return getuserpageview(123, new date()).then(function(pageviews){ var usedcredit=credit-pageviews; if(remainingcredits>0) return remainingcredits+credit; if(credit-usedcredit<=0){ console.log("usedcredit:"+usedcredit); item.set("used",true); return 0; }else{ remainingcredits+=usedcredit; return remainingcredits; } }); }); return parse.promise.when(promises); }).then(function(results){ console.log(_.toarray(arguments)); status.success(); }, function(error){ status.error(error); });
how can calculate remainingcredits specific order?
if important process asynchronously derived data in original items
order, should not processed arrives.
try waiting data arrive, process it.
query.descending("createdat"); return query.find().then(function(items) { return parse.promise.when(_.map(items, function(item) { return getuserpageview(123, new date()).then(function(pageviews) { //here, create object data required later processing return { item: item, pageviews: pageviews }; }); })); }).then(function() { var remainingcredits = 0; var runningbalance _.toarray(arguments).map(function(obj) { var credit = obj.item.get("credit_buy"); var usedcredit = credit - obj.pageviews; if(remainingcredits > 0) return remainingcredits + credit; if((credit - usedcredit) <= 0) { console.log("usedcredit:" + usedcredit); obj.item.set("used", true); return 0; } else { remainingcredits += usedcredit; return remainingcredits; } }); console.log(runningbalance); status.success(); return runningbalance; }, function(error) { status.error(error); });
i invented variable name runningbalance
because appear trying create.
i tried verify processing of credits , can suggest needs looking @ again. example, if usedcredit = credit - obj.pageviews
, test if((credit - usedcredit) <= 0) {...}
simplify if(obj.pageviews <= 0) {...}
, doesn't seem right.
Comments
Post a Comment