Home > Software engineering >  Call async function from another js file in Node.js
Call async function from another js file in Node.js

Time:01-16

Basically, I have several js files, file1.js and files2.js contain async function(DB get), file3.js will call async function in file1.js and get return value, function in file4.js will call file2.js async function to get result and call files3.js function to get result, then process the 2 results and send to browser UI. The schema is similar like below. My question is that can the file3.js and file4.js work? The code structure looks bad, especially the file4.js, where has a "then" hell. Is there any good code structure?

file1.js:

async function func1() {
   ......
   return val1;
}

file2.js:

async function func2() {
   ......
   return val2;
}

file3.js:

const file1 = require('./file1');
function func3() {
   ......
   let func3Val = file1.func1()
     .then(
        function(value) { return value; }
     )
   
   // can func3Val get value above?
   return func3Val   "--hello";
}

file4.js:

const file2 = require('./file2');
const file3 = require('./file3');

const func4= (req, res) => {
   file2.func2().then((ret)=>{
      let test1 = ret;
      ......
      let test2 = file3.func3().then((value) => {
          ......
          res.send([test2 value combined with test1]);
      });
   });

}

CodePudding user response:

I would suggest using async/await instead of the ancient then/catch.

and for method func4, since the value of func2 is not being used in func3, you can use Promise.all to have better style and better performance:

const file2 = require('./file2');
const file3 = require('./file3');

const func4 = async (req, res) => {
   try {
      const [test1, test2] = await Promise.all([file2.func2(), file3.func3()]);
      res.send([test2 value combined with test1]);
   } catch (error) {
      // handle error
   }
}

func3Val in func3 would be undefined, you also need to change it to async/await.

  • Related