The resolve
is an async
method . When you call resolve
method it will register a callback in the callback queue and wait for the resolve method
to complete, once the function is completed it will trigger The callback function.
The Node
will not wait for the callback function, and execute the next statements.
To get the logs statement is sequence and the updated value of the internetConnection
variable. include the last console statement inside the callback.
Example.
var internetConnection = "0"
// Checking the internet connection at the start
require('dns').resolve('www.google.com', function (err) {
if (err) {
internetConnection = "1"
console.log("Internet connection NO", internetConnection)
} else {
internetConnection = "0"
console.log("Internet connection yes ", internetConnection)
}
console.log("Internet connection test", internetConnect
});
Or you could wrap it in a promise object.
const dns = require('dns');
function connectionTest() {
return new Promise((resolve, reject) => {
dns.resolve('www.google.com1', function (err) {
if (err) {
let connectionStatus = 1;
console.log("Internet connection NO", connectionStatus)
reject(connectionStatus);
} else {
let connectionStatus = 0;
console.log("Internet connection yes ", connectionStatus)
resolve(connectionStatus);
}
});
});
}
(async function() {
try {
internetConnection = await connection();
console.log("Internet connection test", internetConnection);
} catch (error) {
internetConnection = error
console.log("Internet connection test", internetConnection);
}
})();