Reputation: 1137
I am wondering why in my example #1 the alerts fire in the proper order 1, 2 but in example #2 where I add an ajax call does the firing order then become 2,1. Also could anyone suggest how with using an ajax call could I achieve the desired firing order of 1, 2... I am stumped.
Example #1
uploader.bind('BeforeUpload', function (up, file, policy, sinature) {
//alert('1');
test();
function test() {
alert('1');
}
});
uploader.bind('UploadFile', function (up, file, policy, signature) {
test2();
function test2() {
alert('2');
}
});
Example #2
uploader.bind('BeforeUpload', function (up, file, policy, sinature) {
//alert('1');
test();
function test() {
data = { alc: 'private', bucket: 'PhotojimaDev', file: file.name, key: path };
$.ajax({
url: sf.getServiceRoot('photojima') + "Upload/getPolicy",
type: 'POST',
data: data,
beforeSend: sf.setModuleHeaders
}).done(function (response, status) {
if (status == "success") {
policy = response.policy;
signature = response.signature;
alert('1');
}
}).fail(function (xhr, result, status) {
alert("Uh-oh, something broke: " + status);
});
}
});
uploader.bind('UploadFile', function (up, file, policy, signature) {
test2();
function test2() {
alert('2');
}
});
Upvotes: 1
Views: 132
Reputation: 3972
The ajax in BeforeUpload
creates a non-blocking background worker that obviously doesn't finish until after UploadFile
If you need BeforeUpload
to finish first, then you will have to tell $.ajax
to not run asynchronously by adding async = false
function test() {
data = { alc: 'private', bucket: 'PhotojimaDev', file: file.name, key: path };
$.ajax({
async: false,
url: sf.getServiceRoot('photojima') + "Upload/getPolicy",
type: 'POST',
data: data,
beforeSend: sf.setModuleHeaders
}).done(function (response, status) {
if (status == "success") {
policy = response.policy;
signature = response.signature;
alert('1');
}
}).fail(function (xhr, result, status) {
alert("Uh-oh, something broke: " + status);
});
}
Search for async in manual: http://api.jquery.com/jQuery.ajax/
Upvotes: 1
Reputation: 12705
ajax
is by default asyn so a ajax request is send and then the code after that is executed
so in the second case you get 2 , 1
because 1 will be fired only when the ajax request a success response
to get the desired 1,2 execution you can call the function test2() from within the success handler
OR
just make the ajax request sync. this can be done setting async to false
when sending the ajax request. but is not recomended
Upvotes: 0