2

I'm a novice in Node JS. I practice promise and I successfully used it. What I understand is with using a promise you can hold the output and send resolve and reject. I used in database operation.

Then someone suggested me to use async/awaits. So here is my code which ran successfully the first time.

shop.js file

const models = require("../models");
const shopModel = models.Shop;
exports.checkShop = function(shopName) {
  return new Promise((reslove, reject) => {
    shopModel
      .findOne({ where: { shop: shopName } })
      .then(rs => {
        if (rs) {
          reslove(rs);
        }
      })
      .catch(err => {
        reject(err.toString());
      });
  });
};

And the file where i called this

const shopController = require("./shop");
exports.getInstall = function(req, res) {

  const shop = req.body.shop;

  if (!cn(shop)) {
    shopController
      .checkShop(shop)
      .then(
        shopCheck =>
          function() {
            if (shopCheck) {
                res.send(`Welcome back ${shopCheck.shop}`);
            } else {
           //my else stuff
            }
          }
      )
      .catch(
        e =>
          function() {
            res.state(500).send(e);
          }
      );
  } else {
    return res
      .status(400)
      .send(
        "Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request"
      );
  }
};

And this is how I tried to replace it with async/awaits. But it does not work.

exports.checkShop = async function(shopName) {
    try{
      var rs = await shopModel.findOne({ where: { shop: shopName } });
      if(rs){
        return rs;
      }
      else{
        return false;
      }
    }
    catch(e){
      return Promise.reject(new Error(400));
    }
};

And the other file

exports.getInstall = function(req, res) {
    const shop = req.body.shop;

    if (!cn(shop)) {
      var shopCheck =  shopController.checkShop(shop);
      try {
        if (shopCheck) {
          res.send(`Welcome back ${shopCheck.shop}`);
        } else {
//         else stuff
        }
      } catch (e) {
        res.state(500).send(e);
      }
    } else {
      return res
        .status(400)
        .send(
          "Missing shop parameter. Please add ?shop=your-development-shop.myshopify.com to your request"
        );
    }
  };
halfer
  • 19,824
  • 17
  • 99
  • 186
Picks Prabhakar
  • 335
  • 1
  • 3
  • 13
  • Promise version of is fine. I'm struggling with async/await version – Picks Prabhakar Jun 23 '19 at 11:54
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! In fact your first snippet does not work because you forgot the `else` path on the `if (rs)` condition. – Bergi Jun 23 '19 at 12:12

1 Answers1

1

Every function with the async keyword before it will (explicitly or implicitly) return a promise.

So when you call shopController.checkShop you will either have to do something like

shopController.checkShop().then(.... )

or make getInstall an async function as well so that you can use await inside it.

exports.getInstall = async function(req, res) {
   // other code here.. 
   const result = await shopController.checkShop(shop);
   //.. 
}

Edit:

If you want to make getInstall async and use await on checkShop you will have to catch the potential rejection using try {} catch like you did in checkShop.

jonahe
  • 4,820
  • 1
  • 15
  • 19
  • That's perfect. But how do i return reject state in async/await? In promise i can simply do reject(error) and then write a catch after then. – Picks Prabhakar Jun 23 '19 at 12:07
  • If you want to make `getInstall` async and use `await` on `checkShop()` you will have to catch the potential rejection using `try {} catch` like you did in `checkShop`. – jonahe Jun 23 '19 at 12:14
  • @PicksPrabhakar You can either `return Promise.reject(…)` like you did, or you can simply `throw …` an exception. – Bergi Jun 23 '19 at 12:14
  • Glad I could help! – jonahe Jun 23 '19 at 12:23