garson garson - 4 months ago 14
Node.js Question

Defining the order of operations in an http.get() request - sync/async issue

I'm retrieving a web address as a URL parameter and then displaying whether the address returns a status code of 200 or not. The trouble is, it seems to only work after a couple seconds--the first time I run it, the code assigning 'mystatus' doesn't seem to be working properly. I feel like there is an issue with the order in which I am running things, but I'm not sure how to fix it.

var express = require("express");
var moment = require("moment");
var http = require("http");
var express = require("express");
var moment = require("moment");
var http = require("http");
var app=express();
var mystatus="";

app.get('/new/:name*', function(req,res){

//detect if name is a URL
//return output
http.get("http:"+req.params[0], function(thisres){
if (thisres.statusCode != 200){
mystatus = "Could not load";
}
else {
mystatus = "Loaded!";
}
}).on('error', function(e){
console.error(e);
})
res.json({url_part1: req.params.name,
url_part2: req.params[0],
status: mystatus
});
})

app.listen(8080, function(){
console.log("App listening on port 8080")
});

Answer

You're running your code node in the promise, so both http.get and res.json are running at the exact same time, so whichever one finishes first it doesn't matter.

Move the res.json response into the promise body of http.get so it will send the response when it gets it

var express = require("express");
var moment = require("moment");
var http = require("http");
var express = require("express");
var moment = require("moment");
var http = require("http");
var app=express();
var mystatus="";

app.get('/new/:name*', function(req,res){

    //detect if name is a URL
    //return output
    http.get("http:"+req.params[0], function(thisres){
        if (thisres.statusCode != 200){
            mystatus = "Could not load";
        }
        else {
            mystatus = "Loaded!";
        }

        res.json({url_part1: req.params.name,
        url_part2: req.params[0],
        status: mystatus
        });
    }).on('error', function(e){
        console.error(e);
    })
})

app.listen(8080, function(){
    console.log("App listening on port 8080")
});