如何在节点js回调函数中减少嵌套循环?

问题描述 投票:1回答:1

请先看一下示例代码。

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............
                  });

             });

         });

      });

    });

});

尽管输出正常,但出现了许多嵌套循环。因为一个输出依赖于另一个功能。我该如何克服这种情况。顺便说一下,我正在使用节点js。谢谢。我要发布另一个示例

    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)

输出:循环内部:10循环外:0

node.js callback node-async
1个回答
0
投票

例如:asyncawait而不是回叫

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()
© www.soinside.com 2019 - 2024. All rights reserved.