Reputation: 161
I have the following code structure :
var firstPagePromise = $.ajax('url1').then(function (data) {
//do stuff
});
var secondPagePromise = $.ajax('url2').then(function (data) {
//do stuff
});
$.when(firstPagePromise, secondPagePromise).done(function () {
// do stuff
});
I want to execute some code after doing two request using JQuery.when() . Written like this, it's working, but I would like to put the two requests in functions for easier maintenance of the code and I'm unsure how to do that.
function fetchFirstPage() {
var firstPagePromise = $.ajax('url1').then(function (data) {
//do stuff
});
return firstPagePromise;
}
var firstPagePromise = fetchFirstPage();
// same for the second page ...
$.when(firstPagePromise, secondPagePromise).done(function () {
// do stuff
});
this does not work and seems to fire when() without waiting for the execution of the two functions, is there any way I could execute the code in the when function only if the two previous function have ended ?
The following code shows my issue on a minimal example, I'd like to get the variable title to print in the console after the call to when but I get "undefined" instead. I think that I understand what's going on, inside the function fetchPage(), title is returned before the request finishes. I think that a callback function could resolve the issue, however, is there any other way ?
function fetchPage() { //fetch the random start page
var title;
var pagePromise = $.ajax('https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&list=random&continue=-||&rnnamespace=0&rnlimit=1').then(function (data) {
title = data.query.random[0].title;
console.log("in request : " + title);
});
console.log("in function return : " + title);
return [title,pagePromise];
}
var firstPageResult = fetchPage();
var title = firstPageResult[0];
var pagePromise = firstPageResult[1];
$.when(pagePromise).done(function() {
console.log("in when : " + title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
Upvotes: 0
Views: 69