Sunday, 14 May 2017

How to return from an inner function (SuperAgent) in nodeJs

        'use strict';
         const express = require('express');
         const app = express();
         var request = require('superagent');


         var list_profs_ues = [
         {
         "id_prof": 0,
         "id_ue": 2   
         },
         {
         "id_prof": 1, 
         "id_ue": 4
         },
         {
         "id_prof": 3,
         "id_ue": 0 
         },      
         {
         "id_prof": 4, 
         "id_ue": 1 
         },
         {
         "id_prof": 2, 
         "id_ue": 3
         }
         ];

        app.get('/service/:name_prof', (req, callback) => { 

        request.get(`http://localhost:5020/service/${req.params.name_prof}`, function(err, res){

        var result_prof_id = res.body.text;
        console.log(result_prof_id);
        var result_ue_id; 

        for (var i = 0; i < list_profs_ues.length; i++){
            if (list_profs_ues[i]["id_prof"] == result_prof_id){    
            console.log(list_profs_ues[i]["id_ue"]);
            result_ue_id = list_profs_ues[i]["id_ue"];
            }}

        request.get(`http://localhost:5030/service/${result_ue_id}`, function(err, res){

            if(err || res.body.text == ""){

            return callback("some result");

            }else{
            return callback("some result");
            }
         });

    });

});
module.exports = app;

const server = app.listen(process.env.PORT || 5040, () => {
console.log('Express server listening on port %d in %s mode', 
server.address().port, app.settings.env);
});

This, displays an error saying : callback is not a function.... My question is quite simple, how can return that "some result" ?? I've tried : return "some result";

Any suggestion will be more than apperciated!



via Ilyes16

No comments:

Post a Comment