Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Synchronous Like Programming in NodeJS / Express with Yield

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);
    }
  }));
res.json(validCoupons);
}));

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

you forgot to send the data or call next, res.send(validCoupons) at the end of your function. should do it

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!