I am using Node.js with cheerio
(a jQuery module on Node.js) and fetch
(a module to get HTML body like request
) to get some data from a website and save into MongoDB.
I can select the elements like jQuery in browsers
I have to get some data
and the pass the data
to a callback
function, something like:
var data = "";
var fetchById = function(id, callback){
var data = $("#"+id).parent().siblings(".someClass").text().replace(/\s/g, ""); // line 3
callback(null, data);
};
and then ...
fetchById(10987, function(err, data){
if(err){
// errorHandle(err);
}else{
// db.save(data);
}
});
But sometimes the callback
is invoked before line 3 has successfully retrieved data
, therefore, data
is an empty string ""
How can I ensure that the callback
is invoked after line 3 is finished?