Node.js - Not running DB promises before returning response





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















I have this request handler on my node server. It has three MongoDB queries, and I want all the results to be returned, before the response is sent.



api.get('/getStats/:productID', (req,res)=>{
let data = {};
let dailySales = ;
let avgProduct = "";
let customers = ;

Sales.find({productID: productID}).then(
sales => {
dailySales = sales;
}
);

Products.find({}).then(
products => {
// Calculate Avg product here
avgProduct = result;
}
);

Customers.find({}).then(
customers => {
customers = customers;
}
);

data = {
dailySales,
avgProduct,
customers
};

res.json(data);
});


But running this returns



data: {
dailySales: ,
avgProduct: "",
customers:
}


i.e. The Mongo response is returning before the data is run. Please how to I fix. Thank You










share|improve this question


















  • 1





    Possible duplicate of How do I return the response from an asynchronous call?

    – Patrick Hund
    Nov 23 '18 at 15:14











  • Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

    – Shilly
    Nov 23 '18 at 15:15




















0















I have this request handler on my node server. It has three MongoDB queries, and I want all the results to be returned, before the response is sent.



api.get('/getStats/:productID', (req,res)=>{
let data = {};
let dailySales = ;
let avgProduct = "";
let customers = ;

Sales.find({productID: productID}).then(
sales => {
dailySales = sales;
}
);

Products.find({}).then(
products => {
// Calculate Avg product here
avgProduct = result;
}
);

Customers.find({}).then(
customers => {
customers = customers;
}
);

data = {
dailySales,
avgProduct,
customers
};

res.json(data);
});


But running this returns



data: {
dailySales: ,
avgProduct: "",
customers:
}


i.e. The Mongo response is returning before the data is run. Please how to I fix. Thank You










share|improve this question


















  • 1





    Possible duplicate of How do I return the response from an asynchronous call?

    – Patrick Hund
    Nov 23 '18 at 15:14











  • Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

    – Shilly
    Nov 23 '18 at 15:15
















0












0








0








I have this request handler on my node server. It has three MongoDB queries, and I want all the results to be returned, before the response is sent.



api.get('/getStats/:productID', (req,res)=>{
let data = {};
let dailySales = ;
let avgProduct = "";
let customers = ;

Sales.find({productID: productID}).then(
sales => {
dailySales = sales;
}
);

Products.find({}).then(
products => {
// Calculate Avg product here
avgProduct = result;
}
);

Customers.find({}).then(
customers => {
customers = customers;
}
);

data = {
dailySales,
avgProduct,
customers
};

res.json(data);
});


But running this returns



data: {
dailySales: ,
avgProduct: "",
customers:
}


i.e. The Mongo response is returning before the data is run. Please how to I fix. Thank You










share|improve this question














I have this request handler on my node server. It has three MongoDB queries, and I want all the results to be returned, before the response is sent.



api.get('/getStats/:productID', (req,res)=>{
let data = {};
let dailySales = ;
let avgProduct = "";
let customers = ;

Sales.find({productID: productID}).then(
sales => {
dailySales = sales;
}
);

Products.find({}).then(
products => {
// Calculate Avg product here
avgProduct = result;
}
);

Customers.find({}).then(
customers => {
customers = customers;
}
);

data = {
dailySales,
avgProduct,
customers
};

res.json(data);
});


But running this returns



data: {
dailySales: ,
avgProduct: "",
customers:
}


i.e. The Mongo response is returning before the data is run. Please how to I fix. Thank You







javascript node.js asynchronous






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 23 '18 at 15:10









Kingsley Kbc ComicsKingsley Kbc Comics

3251417




3251417








  • 1





    Possible duplicate of How do I return the response from an asynchronous call?

    – Patrick Hund
    Nov 23 '18 at 15:14











  • Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

    – Shilly
    Nov 23 '18 at 15:15
















  • 1





    Possible duplicate of How do I return the response from an asynchronous call?

    – Patrick Hund
    Nov 23 '18 at 15:14











  • Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

    – Shilly
    Nov 23 '18 at 15:15










1




1





Possible duplicate of How do I return the response from an asynchronous call?

– Patrick Hund
Nov 23 '18 at 15:14





Possible duplicate of How do I return the response from an asynchronous call?

– Patrick Hund
Nov 23 '18 at 15:14













Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

– Shilly
Nov 23 '18 at 15:15







Promsies will start resolving After the current script finishes, so you hit res.json() before you found anything in the database. As answered below, use Promise.all() to wait for all the database results to return, then use res.json() inside the .then() handler at the end.

– Shilly
Nov 23 '18 at 15:15














3 Answers
3






active

oldest

votes


















1














you can try using the Promise.all where you can pass the MongoDB queries as parameter to it ,the promise will be resolved when all the queries return the result in the array






share|improve this answer
























  • Can I see an example please

    – Kingsley Kbc Comics
    Nov 23 '18 at 15:14











  • looks like @karim had added the code

    – ravi
    Nov 23 '18 at 15:17



















5














wait for all the promises to resolve before sending the actual response



const sales = Sales.find({productID: productID});
const allProducts = Products.find({});
const allCustomers = Customers.find({});

Promise.all([sales, allProducts, allCustomers])
.then(data => res.json(data));





share|improve this answer































    0















    Try using the in-built util.promisify function along with
    async-await to get data correctly!




    const promisify = require('utils').promisify;

    const salesFindOnePromise = promisify(Sales.find);
    const productsFindAllPromise = promisify(Products.find);
    const customersFindAllPromise = promisify(Customers.find);

    findDailySalesByIdAsync = async (productID) => {

    try {
    return await salesFindOnePromise({ productID: productID });
    } catch(err) {
    throw new Error('Could not fetch the appropriate sales with productID');
    }

    }

    findProductsAsync = async () => {

    try {
    return await productsFindAllPromise({});
    } catch (err) {
    throw new Error('Could not fetch sales!');
    }
    }

    findCustomersAsync = async () => {

    try {
    return await customersFindAllPromise({});
    } catch (err) {
    throw new Error('Could not fetch customers!');
    }
    }


    api.get('/getStats/:productID', async (req,res)=>{

    try {
    const dailySales = await findDailySalesByIdAsync(productID);
    const avgProduct = await findProductsAsync();
    const customers = await findCustomersAsync();

    const data = {
    dailySales,
    avgProduct,
    customers
    };

    return res.status(200).send(data);

    } catch(err) {
    console.err(`Failed because: {err}`);
    throw new Error('Could not fetch data because of some error!');
    }

    });





    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449067%2fnode-js-not-running-db-promises-before-returning-response%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      you can try using the Promise.all where you can pass the MongoDB queries as parameter to it ,the promise will be resolved when all the queries return the result in the array






      share|improve this answer
























      • Can I see an example please

        – Kingsley Kbc Comics
        Nov 23 '18 at 15:14











      • looks like @karim had added the code

        – ravi
        Nov 23 '18 at 15:17
















      1














      you can try using the Promise.all where you can pass the MongoDB queries as parameter to it ,the promise will be resolved when all the queries return the result in the array






      share|improve this answer
























      • Can I see an example please

        – Kingsley Kbc Comics
        Nov 23 '18 at 15:14











      • looks like @karim had added the code

        – ravi
        Nov 23 '18 at 15:17














      1












      1








      1







      you can try using the Promise.all where you can pass the MongoDB queries as parameter to it ,the promise will be resolved when all the queries return the result in the array






      share|improve this answer













      you can try using the Promise.all where you can pass the MongoDB queries as parameter to it ,the promise will be resolved when all the queries return the result in the array







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 23 '18 at 15:13









      raviravi

      25828




      25828













      • Can I see an example please

        – Kingsley Kbc Comics
        Nov 23 '18 at 15:14











      • looks like @karim had added the code

        – ravi
        Nov 23 '18 at 15:17



















      • Can I see an example please

        – Kingsley Kbc Comics
        Nov 23 '18 at 15:14











      • looks like @karim had added the code

        – ravi
        Nov 23 '18 at 15:17

















      Can I see an example please

      – Kingsley Kbc Comics
      Nov 23 '18 at 15:14





      Can I see an example please

      – Kingsley Kbc Comics
      Nov 23 '18 at 15:14













      looks like @karim had added the code

      – ravi
      Nov 23 '18 at 15:17





      looks like @karim had added the code

      – ravi
      Nov 23 '18 at 15:17













      5














      wait for all the promises to resolve before sending the actual response



      const sales = Sales.find({productID: productID});
      const allProducts = Products.find({});
      const allCustomers = Customers.find({});

      Promise.all([sales, allProducts, allCustomers])
      .then(data => res.json(data));





      share|improve this answer




























        5














        wait for all the promises to resolve before sending the actual response



        const sales = Sales.find({productID: productID});
        const allProducts = Products.find({});
        const allCustomers = Customers.find({});

        Promise.all([sales, allProducts, allCustomers])
        .then(data => res.json(data));





        share|improve this answer


























          5












          5








          5







          wait for all the promises to resolve before sending the actual response



          const sales = Sales.find({productID: productID});
          const allProducts = Products.find({});
          const allCustomers = Customers.find({});

          Promise.all([sales, allProducts, allCustomers])
          .then(data => res.json(data));





          share|improve this answer













          wait for all the promises to resolve before sending the actual response



          const sales = Sales.find({productID: productID});
          const allProducts = Products.find({});
          const allCustomers = Customers.find({});

          Promise.all([sales, allProducts, allCustomers])
          .then(data => res.json(data));






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 23 '18 at 15:15









          KarimKarim

          5,5621826




          5,5621826























              0















              Try using the in-built util.promisify function along with
              async-await to get data correctly!




              const promisify = require('utils').promisify;

              const salesFindOnePromise = promisify(Sales.find);
              const productsFindAllPromise = promisify(Products.find);
              const customersFindAllPromise = promisify(Customers.find);

              findDailySalesByIdAsync = async (productID) => {

              try {
              return await salesFindOnePromise({ productID: productID });
              } catch(err) {
              throw new Error('Could not fetch the appropriate sales with productID');
              }

              }

              findProductsAsync = async () => {

              try {
              return await productsFindAllPromise({});
              } catch (err) {
              throw new Error('Could not fetch sales!');
              }
              }

              findCustomersAsync = async () => {

              try {
              return await customersFindAllPromise({});
              } catch (err) {
              throw new Error('Could not fetch customers!');
              }
              }


              api.get('/getStats/:productID', async (req,res)=>{

              try {
              const dailySales = await findDailySalesByIdAsync(productID);
              const avgProduct = await findProductsAsync();
              const customers = await findCustomersAsync();

              const data = {
              dailySales,
              avgProduct,
              customers
              };

              return res.status(200).send(data);

              } catch(err) {
              console.err(`Failed because: {err}`);
              throw new Error('Could not fetch data because of some error!');
              }

              });





              share|improve this answer




























                0















                Try using the in-built util.promisify function along with
                async-await to get data correctly!




                const promisify = require('utils').promisify;

                const salesFindOnePromise = promisify(Sales.find);
                const productsFindAllPromise = promisify(Products.find);
                const customersFindAllPromise = promisify(Customers.find);

                findDailySalesByIdAsync = async (productID) => {

                try {
                return await salesFindOnePromise({ productID: productID });
                } catch(err) {
                throw new Error('Could not fetch the appropriate sales with productID');
                }

                }

                findProductsAsync = async () => {

                try {
                return await productsFindAllPromise({});
                } catch (err) {
                throw new Error('Could not fetch sales!');
                }
                }

                findCustomersAsync = async () => {

                try {
                return await customersFindAllPromise({});
                } catch (err) {
                throw new Error('Could not fetch customers!');
                }
                }


                api.get('/getStats/:productID', async (req,res)=>{

                try {
                const dailySales = await findDailySalesByIdAsync(productID);
                const avgProduct = await findProductsAsync();
                const customers = await findCustomersAsync();

                const data = {
                dailySales,
                avgProduct,
                customers
                };

                return res.status(200).send(data);

                } catch(err) {
                console.err(`Failed because: {err}`);
                throw new Error('Could not fetch data because of some error!');
                }

                });





                share|improve this answer


























                  0












                  0








                  0








                  Try using the in-built util.promisify function along with
                  async-await to get data correctly!




                  const promisify = require('utils').promisify;

                  const salesFindOnePromise = promisify(Sales.find);
                  const productsFindAllPromise = promisify(Products.find);
                  const customersFindAllPromise = promisify(Customers.find);

                  findDailySalesByIdAsync = async (productID) => {

                  try {
                  return await salesFindOnePromise({ productID: productID });
                  } catch(err) {
                  throw new Error('Could not fetch the appropriate sales with productID');
                  }

                  }

                  findProductsAsync = async () => {

                  try {
                  return await productsFindAllPromise({});
                  } catch (err) {
                  throw new Error('Could not fetch sales!');
                  }
                  }

                  findCustomersAsync = async () => {

                  try {
                  return await customersFindAllPromise({});
                  } catch (err) {
                  throw new Error('Could not fetch customers!');
                  }
                  }


                  api.get('/getStats/:productID', async (req,res)=>{

                  try {
                  const dailySales = await findDailySalesByIdAsync(productID);
                  const avgProduct = await findProductsAsync();
                  const customers = await findCustomersAsync();

                  const data = {
                  dailySales,
                  avgProduct,
                  customers
                  };

                  return res.status(200).send(data);

                  } catch(err) {
                  console.err(`Failed because: {err}`);
                  throw new Error('Could not fetch data because of some error!');
                  }

                  });





                  share|improve this answer














                  Try using the in-built util.promisify function along with
                  async-await to get data correctly!




                  const promisify = require('utils').promisify;

                  const salesFindOnePromise = promisify(Sales.find);
                  const productsFindAllPromise = promisify(Products.find);
                  const customersFindAllPromise = promisify(Customers.find);

                  findDailySalesByIdAsync = async (productID) => {

                  try {
                  return await salesFindOnePromise({ productID: productID });
                  } catch(err) {
                  throw new Error('Could not fetch the appropriate sales with productID');
                  }

                  }

                  findProductsAsync = async () => {

                  try {
                  return await productsFindAllPromise({});
                  } catch (err) {
                  throw new Error('Could not fetch sales!');
                  }
                  }

                  findCustomersAsync = async () => {

                  try {
                  return await customersFindAllPromise({});
                  } catch (err) {
                  throw new Error('Could not fetch customers!');
                  }
                  }


                  api.get('/getStats/:productID', async (req,res)=>{

                  try {
                  const dailySales = await findDailySalesByIdAsync(productID);
                  const avgProduct = await findProductsAsync();
                  const customers = await findCustomersAsync();

                  const data = {
                  dailySales,
                  avgProduct,
                  customers
                  };

                  return res.status(200).send(data);

                  } catch(err) {
                  console.err(`Failed because: {err}`);
                  throw new Error('Could not fetch data because of some error!');
                  }

                  });






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 15:28









                  Kunal MukherjeeKunal Mukherjee

                  1,94021026




                  1,94021026






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449067%2fnode-js-not-running-db-promises-before-returning-response%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Academy of Television Arts & Sciences

                      L'Équipe

                      1995 France bombings