2013-02-18 6 views
5

Qual è il modo migliore per risolvere il seguente inconvenienza flusso di controllo:condizionalmente l'esecuzione di un callback

  1. voglio solo chiamare getSomeOtherData se someData è uguale a un valore/passa un po 'di test

  2. condizionale In entrambi i casi ho sempre voglia di chiamare getMoreData

http.createServer(function (req, res) { 
    getSomeData(client, function(someData) { 
     // Only call getSomeOtherData if someData passes some conditional test 
     getSomeOtherData(client, function(someOtherData) { 
      // Always call getMoreData 
      getMoreData(client, function(moreData) { 
      res.end(); 
      }); 
     }); 
    }); 
});   

risposta

3

Nessuna grande soluzione a questo; il migliore che ho trovato è quello di rendere una funzione locale che si prende cura del restante lavoro comune come questa:

http.createServer(function (req, res) { 
    getSomeData(client, function(someData) { 
    function getMoreAndEnd() { 
     getMoreData(client, function(moreData) { 
     res.end(); 
     }); 
    } 

    if (someData) { 
     getSomeOtherData(client, function(someOtherData) { 
     getMoreAndEnd(); 
     }); 
    } else { 
     getMoreAndEnd(); 
    } 
    }); 
}); 
2

E 'questo qualcosa che si desidera?

http.createServer(function (req, res) { 
    getSomeData(client, function(someData) { 
     function myFunction (callback) { 
      // Only call getSomeOtherData if someData passes some conditional test 
      if (someData) { 
       getSomeOtherData(client, function(someOtherData) { 
        // Do something. 
       }); 
      } 

      callback(); 
     } 

     myFunction(function() { 
      // Always call getMoreData 
      getMoreData(client, function(moreData) { 
       res.end(); 
      }); 
     }); 
    }); 
}); 
Problemi correlati