Reputation: 41595
I have to load some arrays of data from a DB and i was doing it like this:
var priorities, users;
$.post("http://"+ document.domain + "/priority",
function(dat){
priorities = dat;
});
$.post("http://"+ document.domain + "/users",
function(dat){
users= dat;
});
Then i want to use this variables inside a plugin and I realized the plugin gets fired before this variables are set even the this code is at the start of the JS file.
Is there any better way to load an array of data from a DB? In case there is not, how can I do to set this variables before any other code gets executed?
Thanks.
Upvotes: 0
Views: 70
Reputation: 18848
Sounds like you want jQuery deferred objects.
var priorities, users;
$.when(
$.post("foo", function(data) { priorities = data; } ),
$.post("bar", function(data) { users = data; } )
).done(function() {
someFunction(priorities, users); // Call your function. Values are set!
})
This will only call someFunction
when all the post()
functions have been resolved. You can then store the data received in the post()
function in a higher scope, and access them inside someFunction()
.
Upvotes: 1
Reputation: 26930
$.post("http://"+ document.domain + "/priority",
function(priorities){
$.post("http://"+ document.domain + "/users",
function(users){
DoSomething(priorities, users);
});
});
function DoSomething(priorities, users){
// User Priorities and Users here
}
Other option is to call ajax synchronously, but I don't suggest that :)
EDIT:
var priorities, users;
function getPriority(){
$.post("http://"+ document.domain + "/priority",
function(dat){
priorities = dat;
});
}
function getUsers(){
$.post("http://"+ document.domain + "/users",
function(dat){
users= dat;
});
}
var dfd = $.Deferred();
dfd
.done([getPriority, getUsers])
.done(function() {
//here you will have priorities and users
});
dfd.resolve();
Upvotes: 1
Reputation: 3550
You would want to use a control flow library, I personally enjoy using async https://github.com/caolan/async which works both in the browser and on the server side.
Using Async
async.waterfall([
function(callback){
$.post("http://"+ document.domain + "/priority", function(dat){
callback(null, dat);
});
},
function(priorities, callback){
$.post("http://"+ document.domain + "/users", function(dat){
callback(null, priorities, dat);
});
}
], function (err, priorities, users) {
//work with users & priorities
});
Using Callbacks
$.post("http://"+ document.domain + "/priority", function(priorities){
$.post("http://"+ document.domain + "/users", function(users){
//work with users & priorities
});
});
The reason your running into the problem is because ajax operations are executed async, in that the code does not wait for the operation to be completed but instead fires the callback.
Upvotes: 1