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?
You can accomplish this by explicit queueing. See jQuery API.
For example (from the API):
$( "#foo" ).slideUp();
$( "#foo" ).queue(function() {
alert( "Animation complete." );
$( this ).dequeue();
});
Which is the same as executing .slideUp()
first and then, as a callback, executing the alert()
.
As for you code, this would turn into something like this:
var data = 0;
$("#some_element").queue("yourQueue", function() {
console.log("First");
// first function
data = $("#"+id).parent().siblings(".someClass").text().replace(/\s/g, "");
$(this).dequeue("yourQueue");
});
$("#some_element").queue("yourQueue", function() {
console.log("Second");
// second function
callback(null, data); // if callback() is a declared function, this should work
$(this).dequeue("yourQueue");
});
$("#some_element").dequeue("yourQueue");
Where I used the code from this answer: How do I chain or queue custom functions using JQuery?
Important to note here, is that the .queue()
function must be called on the same global element, to make sure the functions are executed (explicitly) sequential.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments