2

For some reason, in node.js, the code is not running in order. It is running the console.log(data2) before even retrieving the data from function2. I am assuming it is because node.js runs asynchronously. However, I am not too sure how to fix it. Thanks for all the help in advance

function function1(app){
    app.post('/test', (req, res, next) => {
        const url = `url1`;
        request(url, function(error, response, body) {
            if(!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                var data2 = function2(data.id);
                console.log(data2); //undefined  
                res.send(profileData);
            }
        });
    })
}

function function2(id){
    const url = `url2/${id}`;
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            console.log(data); //output correct data
            return data;
        }
    });
}
James Lee
  • 656
  • 1
  • 7
  • 22
  • 1
    See: https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – NullDev Jun 27 '20 at 22:27
  • You are right. Because it works async, it actually runs in order without waiting for response of your function2. Node.js just calls your function2 and moves on, if you want it to wait or use the data that comes from an async call, you should use promises (async/await or then) or callbacks. See the comment above and i would also recommend you to look at Promise.all. – TheInformedMan Jun 27 '20 at 22:31
  • Bit of a misconception that *node* runs asynchronously...it is the specific request methods you are using that do – charlietfl Jun 27 '20 at 22:43

2 Answers2

2
function function1(app){
    app.post('/test', (req, res, next) => {
        const url = `url1`;
        request(url, async function(error, response, body) {
            if(!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                var data2 = await function2(data.id);
                console.log(data2); //undefined  
                res.send(profileData);
            }
        });
    })
}


function function2(id) {
  const url = `url2/${id}`;
  return new Promise(function (resolve, reject) {
    request(url, function(error, response, body) {
      if(!error && response.statusCode == 200) {
        resolve(JSON.parse(body));
      } else {
        reject(error);
      }
    });
  });
}
blex
  • 24,941
  • 5
  • 39
  • 72
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54
0

Because you're calling function2() just before outputting console.log(data2). The latter gets executed immediately, while the former has to make a server request. Pass data2 to function2() instead and output it after you output the result from function2()

function function1(app){
    app.post('/test', (req, res, next) => {
        const url = `url1`;
        request(url, function(error, response, body) {
            if(!error && response.statusCode == 200) {
                var data = JSON.parse(body);
                var data2 = function2(data.id, data2);
                res.send(profileData);
            }
        });
    })
}

function function2(id, data2){
    const url = `url2/${id}`;
    request(url, function(error, response, body) {
        if(!error && response.statusCode == 200) {
            var data = JSON.parse(body);
            console.log(data); //output correct data
            console.log(data2); //undefined  
            return data;
        }
    });
}
symlink
  • 11,984
  • 7
  • 29
  • 50