Search code examples
javascriptnode.jstypeorm

Typeorm complex query with promise chain


I am getting data from multiple tables in typeorm like this :

Order.findOne(orderId).then(order => {
  Stuff.findOne(order?.stuffId).then(stuff => {
    Site.findOne(stuff?.storeId).then(store => {
      Stuff.findOne(order?.stuffId).then(stuff1 => {
        Ware.findOne(stuff1?.wareId).then(ware => {
          Site.findOne(order?.unitId).then(unit => {
            Organization.findOne(order?.organizationId).then(
              organization => {
                // do some stuff with returned values       
              });
          });
        });
      });
    });
  });
});

Now I know this is a bad code (too error-prone and confusing). I'm looking for a more convenient way to achieve this (getting multiple data from multiple tables) in typeorm.

Any advice would be helpful.


Solution

  • async function fectchAndExecute() {
      let order = await Order.findOne(orderId);
      let stuff = await Stuff.findOne(order ? .stuffId);
      let store = await Site.findOne(stuff ? .storeId);
      let ware = await Ware.findOne(stuff?.wareId);
      let unit = await Site.findOne(order?.unitId);
      let organization = await Organization.findOne(order?.organizationId);
      // do some stuff with returned values 
    };
    

    You can call this function.

    Notice you do not need to name stuff as stuff1 again since you can use it already with stuff var.