dmfay is correct that the asynchronous T.get() function is tripping you up.
Check out MDN's write-up on the concurrency model
JavaScript runs from an event loop where messages are processed from a queue. Each message is associated with a function. When the stack has capacity, a message is pulled from the queue and processed.
Every message is processed to completion, and messages can be added to the queue by functions, including functions that will be processed asynchronously like your T.get() function. In this case, if there are no other messages, T.get() is processed right away, but if there are other messages such as console.log('third call'), T.get() has to wait to insert it's message into the the stack, and it has to wait for it's callbacks to complete before it can invoke console.log().
function findTweets(params, num)
{
params = {
q: params,
count: num ,
language: 'en'
}
T.get('search/tweets', params, function(err, data, response) {
console.log("first call"); // 3. Ok, I'm done!
});
console.log("second call"); // 4. Finally!
}
findTweets("a str",1) //1. I can start now but can't finish until my callbacks do
console.log("third call"); // 2. Sweet! I can go right now.
How can you get these to execute in the order you expect? Try a promise and a callback.
In order to see this in action, I stubbed the twitterAPI function with an object that contains the get() method. The stubbed get() method spoofs a delayed response using setTimeout()
var twitterAPI = function () {
this.get = function (method, params, callback) {
setTimeout(function () {
callback()
}, 1000)
}
}
var T = new twitterAPI()
function findTweets (params, num, callback) {
params = {
q: params,
count: num,
language: 'en'
}
var p1 = new Promise(function(resolve, reject) {
T.get('search/tweets', params, function (err, data, response) {
resolve("first call") // first call resolved as a promise
})
})
p1.then(function(res) {
console.log(res) // log resolved promise
console.log("second call") // make second call
return callback() // return callback so third call can go
})
}
findTweets("a str", 1, function () {
console.log("third call") // Finally, third call is called
})
/*
first call
second call
third call
*/