Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda