Home > Software design >  multiple IF conditions execute one by one in nodejs using Async/await
multiple IF conditions execute one by one in nodejs using Async/await

Time:06-05

How can i run this if statements synchronously. I have been trying many times but unable to fixed this. (I am nodejs beginner). i am trying to use async/await here but it is not work. how can i check first if condition is completed and then second if statement will run! Please help. here is my dummy codes:

record1='10';
record2='20';

function main(){

      if(record1){
        console.log('-------------------------');
        console.log('I am record 1')
        val='John',
        firstJob(val)
        
      }

      if(record2){
        console.log('I am record 2')
        val='Rahul',
        firstJob(val)
      }
}

 async function firstJob(val){
 
  console.log('Hello, I am '   val)
  await secondJob(val);

}

async function secondJob(val){
 
  console.log(val  ' is a nodeJs beginner!')
  await listFiles()

}

 function thirdJob(arg){
  if (arg='pass'){
     console.log('This is end of the one if condition')
  }
}


 function  listFiles (){ 
      return new Promise((resolve, reject) => {
      setTimeout(() => {
      const path = require('path');
      const fs = require('fs');
      const { exit } = require('process');
      const  directoryPath = path.join(__dirname, '../');
      console.log('List of Avaialble Files :');
      fs.readdir(directoryPath, { withFileTypes: true },function (err, files) {
          if (err) {
              return console.log('Unable to scan directory: '   err);
          } 
          files.forEach(function (file) {
              if (file.isFile()){
                  console.log(file);
              } 
          });
      });
      arg='pass'
      thirdJob();
      
    }, 2000)
  })

}

main();

CodePudding user response:

The short answer is you can't "make them run synchronously". You have to patiently wait until they're done to get the answer.

So, without making main async, you have to use the promises the old fashioned way, and sequence the actions using then.

record1='10';
record2='20';

function main(){

  Promise.resolve()
    .then(() => {
      if(record1){
        console.log('-------------------------');
        console.log('I am record 1');
        val='John';
        return firstJob(val)
      }
    })
    .then(() => {
      if(record2){
        console.log('I am record 2')
        val='Rahul';
        return firstJob(val)
      }
    });
}

 async function firstJob(val){

  console.log('Hello, I am '   val)
  await secondJob(val);

}

async function secondJob(val){

  console.log(val  ' is a nodeJs beginner!')
  await listFiles()

}

main();

I've just included the snippet for the if and promise stuff. The gist here is that you conditionally chain together your calls to firstJob.

Each call to then allows you to (potentially, it's not required) attach another promise to the execution of the one that just finished. In the snippet above, we're doing that only if the condition is truthy by returning the promise from the calls to firstJob.

By the way, your implementation of listFiles isn't ever going to finish because you never invoke resolve to the promise you made inside the function. This solves the problem by resolving your promise once the looping is done.

function  listFiles (){ 
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const path = require('path');
      const fs = require('fs');
      const { exit } = require('process');
      const  directoryPath = path.join(__dirname, '../');
      console.log('List of Avaialble Files :');
      fs.readdir(directoryPath, { withFileTypes: true },function (err, files) {
        if (err) {
          console.log('Unable to scan directory: '   err);
          reject(err);
        } 
        files.forEach(function (file) {
          if (file.isFile()){
            console.log(file);
          } 
        });
        resolve();
      });
      arg='pass'
      thirdJob();
      
    }, 2000)
  })

}

Note the added call to resolve once you've completed your loop. I also added a call to reject in the case that readdir returned an error, since that is the proper way to propagate it with your manual promise.

A few more pointers, generally modules are required once at the top of the file, instead of dynamically inside of a function. The penalty for doing it that way you have is not bad, there is a cache for required modules. It's just not idiomatic.

if (arg='pass'){

Doesn't do any equality check, that's an assignment, you need ==, or === if you want to check for equality.

  • Related