I'm having a really hard time with Node Asynchronous operation (coming from a PHP background). I know that you can nest callbacks but that can get out of hand really quickly.
Here is a basic example I want to solve synchronously (I know it might be simple to solve asynchronously for this example but I need to know how to do it synchronously for more complicated projects).
This is an express app where i'm trying to count the number of times a coupon has been used:
var express = require('express');
var wrap = require('co-express');
app.post('/grab-valid-coupons', wrap(function* (req, res) {
var validCoupons = [];
console.log('grabbing coupons');
var coupons = yield db.collection('Coupons').find({}).toArray();
coupons.forEach(wrap(function* (coupon, index) {
console.log(coupon.code, 'CODE');
var couponUse = 0;
couponUse += yield db.collection('Rentals').find({coupon: coupon.code}).count();
couponUse += yield db.collection('Orders').find({coupon: coupon.code}).count();
console.log(couponUse);
if(couponUse < coupon.uses) {
validCoupons.push(coupon);
}
}));
}));
The first yield is working but the part where I try and get the count of everything is causing the entire server to hang. Any ideas?
via Jordash
No comments:
Post a Comment