javascript
  • node.js
  • asynchronous
  • 2013-06-21 13 views 8 likes 
    8

    Una chiamata API restituisce la "pagina" successiva dei risultati. Come posso ricorrere elegantemente a tale callback del risultato?Come recitare in modo asincrono tramite callback API in node.js?

    Ecco un esempio di cui ho bisogno di fare questo:

    var url = 'https://graph.facebook.com/me/?fields=posts&since=' + moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken; 
    request.get({ 
        url: url, 
        json: true 
    }, function (error, response, body) { 
        if (!error && response.statusCode == 200) { 
         _.each(body.posts.data, function (post) { 
          User.posts.push(post); //push some result 
         }); 
         if (body.pagination.next) { // if set, this is the next URL to query 
          //????????? 
         } 
        } else { 
         console.log(error); 
         throw error; 
        } 
    
    }); 
    

    risposta

    17

    Vorrei suggerire avvolgendo la chiamata in una funzione e solo continuare a chiamarlo finché non è necessario.

    Vorrei anche aggiungere un callback per sapere quando il processo è terminato.

    function getFacebookData(url, callback) { 
    
        request.get({ 
         url: url, 
         json: true 
        }, function (error, response, body) { 
         if (!error && response.statusCode == 200) { 
          _.each(body.posts.data, function (post) { 
           User.posts.push(post); //push some result 
          }); 
          if (body.pagination.next) { // if set, this is the next URL to query 
           getFacebookData(body.pagination.next, callback); 
          } else { 
           callback(); //Call when we are finished 
          } 
         } else { 
          console.log(error); 
          throw error; 
         } 
    
        }); 
    } 
    
    var url = 'https://graph.facebook.com/me/?fields=posts&since=' + 
        moment(postFromDate).format('YYYY-MM-DD') + '&access_token=' + User.accessToken; 
    
    getFacebookData(url, function() { 
        console.log('We are done'); 
    }); 
    
    +0

    Perfetto, grazie. Così ovvio ora. Per inciso - c'è una ragione per cui userei la funzione getFacebookData() vs var getFacebookData = function() in questo caso? – metalaureate

    +1

    Nessun motivo difficile solo quelli morbidi e quelli sono - In primo luogo è almeno per me un modo più naturale di definire una funzione, in secondo luogo se si dovesse dimenticare la "var", allora sarebbe diventata una funzione globale. E terzo e più utile: se dichiarato in questo modo, la funzione avrà un nome invece di essere anonimo. Questo ha i suoi usi. E il più semplice dei quali è - verrà visualizzato nella traccia dello stack. – DeadAlready

    Problemi correlati