skip to Main Content

I’m creating a application for client. and I’m using koa.js mongodb(for database) in application.I’m trying to get customers details with total reminders with specific customers but koa is not waiting for promise and returning "[]" in response whenever i try to call that route

here’s my code

    router.get("/getcustomers",async (ctx)=>{
      ctx.customers = [await remind_col.find({}).toArray()][0];
      ctx.customeralgo = [];
      new Promise((reso,reje)=>{ 
        ctx.customers.map(async cust=>{
          return {
            email:cust.email,
            first_name:cust.first_name,
            last_name:cust.last_name,

             //------------- This is the when I'm trying to get count for customer
            total_reminders:[await remind_col.count({"email":cust.email})][0],
            //----------------
          }
        })
      }).then(rlt=>{
        ctx.customeralgo = rlt;
        console.log(rlt);
        ctx.body = ctx.customeralgo;
      })

    })

and this is response image when I call this route:

enter image description here

2

Answers


  1. Try Promise.all instead new Promise

    router.get("/getcustomers", async (ctx) => {
      ctx.customers = [await remind_col.find({}).toArray()][0]
      ctx.customeralgo = []
      const promises = ctx.customers.map(async cust => ({
        email: cust.email,
        first_name: cust.first_name,
        last_name: cust.last_name,
        // ------------- This is the when I'm trying to get count for customer
        total_reminders: [await remind_col.count({ "email": cust.email })][0],
        //----------------
      }))
      Promise.all(promises).then(rlt => {
        ctx.customeralgo = rlt
        console.log(rlt)
        ctx.body = ctx.customeralgo
      })
    })
    
    Login or Signup to reply.
  2. You have a bunch of extra things there.

    What is the idea behind this?

    ctx.customers = [await remind_col.find({}).toArray()][0];
    

    If this part remind_col.find({}).toArray() returns an array why you are putting inside array and then getting the first element?

    I strongly believe, you can simply use this below

    const customers = await remind_col.find({}).toArray();
    

    Since it is not a middleware you don’t need to assign anything to the context object.

    You defined promise but never resolve a value.

    I clean your code a bit and I assume this would work for you

    router.get('/getcustomers', async (ctx) => {
      const customers = await remind_col.find({}).toArray();
      const transformedCustomers = customers.map(async (customer) => ({
        email: customer.email,
        first_name: customer.first_name,
        last_name: customer.last_name,
        total_reminders: await remind_col.count({ email: customer.email }),
      }));
    
      ctx.body = await Promise.all(transformedCustomers);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search