1

Please take a look at the sample code first.

TestFunc1(user, result, date, function (response) {
   let x = response;
       TestFunc2(x, function (response) {
        let y = response; 
          TestFunc3(y, function (response) {
           let z = response;
            TestFunc4(z, function (response) {
             let p = response;
                TestFunc5(p, function (response) {
                   let q = response;
                    TestFunc6(q, function (response) {
                     let r = response;
                      //continue............
                  });

             });

         });

      });

    });

});

Although the output is ok but a lot of nested loop has come. because ones output depend on another function. How can I overcome this situation. By the way I am using node js. Thank you. I am posting another sample

    let cycle= 0;
    let sql= 'SELECT * FROM table limit 1';    
    client.query(sql, function (err, result) {
    if (err) throw err;
    result.rows.forEach(row => {
      cycle= Number(row["cycle"]);
      console.log('cycle inside:', +cycle)
    }); 
    console.log('cycle outside:', +cycle)

Output: cycle inside:10 cycle outside:0

Suman Kumar Dash
  • 681
  • 5
  • 19

1 Answers1

1

Ex : async and await instead of call back

const tes1 = () => {
     return { test1 : 'test1' }
 }

 const test2 = (p1) => {
     try{
        if(typeof p1 !== 'undefined'){
            return { test2 : 'test2', p1 }
        }else{
            throw new Error('custom error')
        }
     }catch(err){
         throw err
     }

 }

 const mainFunc = async () => {
    try{
        const t1 = await tes1()        
        const t2 = await test2(t1)

        console.log('t1', t1)
        console.log('t2', t2)
        console.log('done')

    }catch(err){        
        // error handle here 
        console.log('err', err)
    }
 }

 // call func
 mainFunc()
Amila Sampath
  • 655
  • 4
  • 11
  • 28
  • It is not work for following code: await db.query(sql_cycle_time, function (err, result) { if (err) throw err; result.rows.forEach(row => { cycleTime = Number(row["scoring_cycle"]); return cycleTime; }) – Suman Kumar Dash Dec 26 '19 at 09:01
  • getData = (query_str) => { return new Promise(function(resolve, reject) { db.query(query_str, query_var, (err, rows, fields) => { // Call reject on error states, // call resolve with results if (err) { return reject(err); } // do your process here resolve(rows); }); }); } – Amila Sampath Dec 26 '19 at 09:20
  • const dbData = await getData(t2) – Amila Sampath Dec 26 '19 at 09:21