Reputation: 334
Im new to Nodejs and was wondering why the functions execute out of order instead of how ive written it:
var tor_proxy = require("tor-request")
var s = require("sleep");
tor_proxy.setTorAddress("localhost", 9050);
tor_proxy.TorControlPort.password = "password";
function ShowIP() {
tor_proxy.request("http://ident.me", function(err, response, body) {
if(!err && response.statusCode == 200) {
console.log(body);
}
});
}
function Renew() {
tor_proxy.renewTorSession(function() { console.log("renewed"); });
}
ShowIP();
Renew();
ShowIP();
//Id Like It To Show The IP Then Renew Then Show The New IP
//But Instead It's Out Of Order
Nodejs is event driven (correct me if im wrong) and any help will be appreciated. Thanks :)
Upvotes: 0
Views: 820
Reputation: 234
The script will be executed like this:
ShowIP()
, tor_proxy.request()
sends a request to http://ident.me .Renew()
is executed.tor_proxy.renewTorSession()
is likely to be an asynchronous function. If so, after it begins, the next ShowIP()
will be executed without waiting for renewTorSession()
to complete.Depending on how fast http://ident.me replies and how fast renewTorSession()
completes, the results may vary.
To execute these functions in proper order, you can search for the following keywords:
Promise
Async
/Await
An example using promise
, async
and await
:
var tor_proxy = require('tor-request');
tor_proxy.setTorAddress('localhost', 9050);
tor_proxy.TorControlPort.password = 'password';
function ShowIP() {
return new Promise((resolve, reject) => {
tor_proxy.request('http://ident.me', function (err, response, body) {
if (err) reject(err);
else if (response.statusCode !== 200) reject('response.statusCode: ' + response.statusCode);
else {
console.log(body);
resolve();
}
});
});
}
function Renew() {
return new Promise((resolve, reject) => {
tor_proxy.renewTorSession(() => {
console.log('renewed');
resolve();
});
});
}
async function testFunction() {
// Await makes sure the returned promise completes before proceeding.
// Note that await keyword can only be used inside async function.
try {
await ShowIP();
await Renew();
await ShowIP();
console.log('done!');
} catch (error) {
console.log(error);
}
}
testFunction();
Upvotes: 2