0

I'm trying to make a function that checks if the given URL is working or not. This is what I've done so far:

function checkWebsite(url) {
  http
    .get(url, function(res) {
      console.log(url, res.statusCode);
      return res.statusCode === 200;
    })
    .on("error", function(e) {
      return false;
    });
}

I want to wait until http get is finished and then return true or false based on the status code and being the response in a callback function I don't know how to return it back to where it was called. Example call:

function test() {
   if (checkWebsite("https://stackoverflow.com/")) {
    return "https://stackoverflow.com/";
   } 
}

I want to get the true or false in this if statement but since the status code is in a callback function I don't know how to return it.

Leonardo Drici
  • 749
  • 3
  • 11
  • 32
  • I've tried that but I wasn't able to make it work. Could you please give me an example? – Leonardo Drici Feb 17 '19 at 18:38
  • No answer here will add any information to the answers in the related discussion. Take your time and read them, all the information you need is there. – Azami Feb 17 '19 at 18:40
  • Re read it and still no help... I need to return the status code but it is in a callback function – Leonardo Drici Feb 17 '19 at 18:50
  • You can't wait and then return without using a spinlock, which is a very bad idea , since you have no reason to ever wait and then return in JavaScript. Like the linked answers explain, hust use the callback or use a Promise . – Paul Feb 17 '19 at 18:59

1 Answers1

3

I'll give you a working snippet since you cannot figure it out from the linked answer, maybe it'll help you more:

var http = require('http');
var https = require('https');

test();

function checkWebsite(url, callback) {
  https
    .get(url, function(res) {
      console.log(url, res.statusCode);
      return callback(res.statusCode === 200);
    })
    .on("error", function(e) {
      return callback(false);
    });
}

function test(){
    checkWebsite("https://stackoverflow.com/", function(check){
        console.log(check); //true
    })
}

With promises:

var http = require('http');
var https = require('https');

test();

function checkWebsite(url) {
    return new Promise((resolve, reject) => {
      https
        .get(url, function(res) {
          console.log(url, res.statusCode);
          resolve(res.statusCode === 200);
        })
        .on("error", function(e) {
          resolve(false);
        });     
    })
}
async function test(){
    var check = await checkWebsite("https://stackoverflow.com/");
    console.log(check); //true
}
Azami
  • 2,122
  • 1
  • 12
  • 22