How show alert after ajax post loop done ? Javascript [duplicate] - javascript

loadInfo: function(){
var jsonCounter = 0,
room = ['room1','room2','room3'],
dates = [],
prices = []
$.each(booking.rooms, function(key, room_name) {
$.getJSON('/get_info.php?room='+room_name, function(data) {
dates[room_name] = data
jsonCounter++
})
$.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
prices[room_name] = data
jsonCounter++
})
})
function checkIfReady() {
if (jsonCounter === rooms.length * 2) {
clearInterval(timer)
run_the_rest_of_the_app()
}
}
var timer = setInterval(checkIfReady, 100)
}
(Modified a lot, as it's part of a class etc etc.)
At the moment this feels a bit hackish, as the timer usage seems rubbish. I would use $.when and $.done, but I don't know how many rooms there might be, so I don't know what to put into when.
How do I ensure that run_the_rest_of_the_app() only gets called once all of the AJAX requests come back?

var activeAJAX = 0;
Before making an AJAX call, activeAJAX++;
After completing an AJAX call (in the callback): if (--activeAJAX == 0) { allDone(); }

Here is how to use when/done
loadInfo: function(){
var room = ['room1','room2','room3'],
dates = [],
prices = [],
requests = [];
$.each(booking.rooms, function(key, room_name) {
var aRequest;
aRequest = $.getJSON('/get_info.php?room='+room_name, function(data) {
dates[room_name] = data;
});
requests.push(aRequest);
aRequest = $.getJSON('/get_info.php?room='+room_name+'&prices', function(data) {
prices[room_name] = data;
});
requests.push(aRequest);
})
$.when.apply($, requests).done(run_the_rest_of_the_app);
}

Related

Javascript Promise.all - how can I make this existing function synchronous?

I have a function which works fine when its ran synchronously, but as soon as I make it asynchronous it fails to work because it is returning true before all images are loaded.
Here is the original function which existed:
if (window.num_alt > 0) {
var div = document.getElementById('productImageLarge');
if (div) {
var html = '';
colour = colour || '';
var tmp = getTemplate('image_holder');
if (!tmp) { tmp = 'image_holder is missing<br>'; }
// num_alt same number as images - use this for the loop
for (var i=0; i<num_alt-0+1; i++) {
var tmp1 = tmp;
tmp1 = tmp1.replace(/\[xx[_ ]image\]/ig, imagename+colour+alt_ext[i]);
tmp1 = tmp1.replace(/\[xx[_ ]img_no\]/ig, i);
html += tmp1;
// at the end of the loop
if (i == num_alt) {
imagesDone = true;
}
}
div.innerHTML = html;
}
}
return imagesDone;
Basically it takes the num_alt images set in a variable (set to 8) and fills in a JS template. Once its at the end of the loop I have another function on an interval testing whether imagesDone == true. Once it is set to true, the function fires and the image slider kicks in.
I wanted to lazy-load the images, and for some reason the current function wouldn't allow me to do this without trying to load images that return a 404. So I converted the function to use promises which calls itself until all images are processed (removed the for loop) and this has worked for a while, but its using async:false....
var imagesDone = false;
//console.log("Create Image");
if (window.num_alt > 0) {
var div = document.getElementById('productImageLarge');
if (div) {
var html = '';
colour = colour || '';
var tmp = getTemplate('image_holder');
if (!tmp) { tmp = 'image_holder is missing<br>'; }
var i = 0;
var promises = [];
function ajax_data() {
promises.push($.ajax({
url: thisUrl+'product-image.php?size=large&image=/'+imagename+colour+alt_ext[i]+'.jpg',
method: 'post',
data: promises,
async : false,
success: function (resp) {
if (i<=num_alt) {
var tmp1;
tmp1 = tmp;
tmp1 = tmp1.replace(/\[xx[_ ]image\]/ig, imagename+colour+alt_ext[i]);
tmp1 = tmp1.replace(/\[xx[_ ]img_no\]/ig, i);
html += tmp1;
div.innerHTML = html;
i++;
ajax_data();
}
}
}))
}
Promise.all([ajax_data()])
.then([imagesDone = true])
.catch(e => console.log(e));
}
}
return imagesDone;
If I remove the async:false, imagesDone is returned too soon and the slider function kicks in to early. Can anyone help me understand how to make this work in a synchronous / chained fashion? I've been trying for a while but just can't seem to get it to work.
Thanks in advance.
It's not clear what you want to do, your code looks like part of a function that already doesn't do what you want it to do. Maybe the following will work for you:
var Fail = function(reason){this.reason=reason;};
var isFail = function(o){return (o||o.constructor)===Fail;};
var isNotFail = function(o){return !isFail(0);};
//...your function returning a promise:
var tmp = getTemplate('image_holder') || 'image_holder is missing<br>';
var div = document.getElementById('productImageLarge');
var html = '';
var howManyTimes = (div)?Array.from(new Array(window.num_alt)):[];
colour = colour || '';
return Promise.all(//use Promise.all
howManyTimes.map(
function(dontCare,i){
return Promise.resolve(//convert jQuery deferred to real/standard Promise
$.ajax({
url: thisUrl+'product-image.php?size=large&image=/'+imagename+colour+alt_ext[i]+'.jpg',
method: 'post',
data: noIdeaWhatYouWantToSendHere//I have no idea what data you want to send here
// async : false //Are you kidding?
})
).catch(
function(error){return new Fail(error);}
);
}
)
).then(
function(results){
console.log("ok, worked");
return results.reduce(
function(all,item,i){
return (isFail(item))
? all+"<h1>Failed</h1>"//what if your post fails?
: all+tmp.replace(/\[xx[_ ]image\]/ig, imagename + colour + alt_ext[i])
.replace(/\[xx[_ ]img_no\]/ig, i);
},
""
);
}
).then(
function(html){
div.innerHTML=html;
}
)
There are many issues in the code above, indicating that you may need to understand better how Promises work. Your function should probably return the Promise so that the caller handle the asynchronicity on their side.
So either use:
return Promise.all(promises);
or:
return Promise.all(promises).then(function() { return true; })

Fill/Generate multiple jQuery elements and sort them after ajax requests

I've got some IDS that I want to use to fill / generate some jQuery Objects. I use these IDS in ajax requests.
After the jQuery Objects have been filled, I want to sort them.
Has to work in IE11.
What my problem is:
At the moment I've no idea how the best practice would look like, to wait for all ajax requests and as well all jQuery objects to be filled.
I have to wait until all ajax requests have been completed (so
always, indepedent from response code (so on .done and .fail))
I have to wait until all
jQuery Objects are filled with the results from the ajax Requests
Problem conclusion: sort function is called before the items are filled.
I've tried to break down my whole code to a simple example, maybe someone can help here:
function sortEntries(a, b) {
var aa = ($(a).data('name') || '').toLowerCase(),
bb = ($(b).data('name') || '').toLowerCase();
return aa < bb ? -1 : aa > bb ? 1 : 0;
}
function getEntryInfo(infoObj, callback) {
function getLabelByResult(result) {
var name = '';
switch (result) { // For this demo, we don't use the response data.
case 'page-header':
name = 'Hello World 1';
break;
case 'thumbnails':
name = 'It works!';
break;
case 'nav':
name = 'Great!';
break;
case 'btn-groups':
name = 'BTN GROUP';
break;
default:
name = 'NOT SET!'
}
return name;
}
return $.ajax({
method: 'GET',
url: infoObj.URI,
cache: false
}).done(function(data) {
if ($.isFunction(callback)) {
callback(true, {
name: getLabelByResult(infoObj.element)
});
}
}).fail(function() {
if ($.isFunction(callback)) {
callback(false, {
name: getLabelByResult(infoObj.element)
});
}
});
}
function setInfoForEntry(item$, config) {
return getEntryInfo(config, function(isOk, responseObjInfo) {
item$.attr('data-name', responseObjInfo.name || '').text(responseObjInfo.name || '');
});
}
function generateItems() {
var parentItem$ = $('body').append($('<ul/>').addClass('allItems').hide()),
ids = ['page-header', 'thumbnails', 'nav', 'btn-groups'], // for testing purposes of course
requests = [],
extractedItems$;
$.each(ids, function(ignorel, el) {
var newItem$ = $('<li/>').addClass('idItem').on('click', function(e) {
alert($(e.currentTarget).data('name'));
});
parentItem$.append(newItem$);
requests.push(setInfoForEntry(newItem$, {
URI: 'https://getbootstrap.com/docs/3.3/components/#/' + el,
element: el
}));
});
// HERE I HAVE TO ENSURE THAT:
// -ALL AJAX REQUESTS ARE DONE
// -ALL jQuery Elements are filled
extractedItems$ = parentItem$.find('.idItem');
extractedItems$.sort(sortEntries);
extractedItems$.detach().appendTo(parentItem$);
parentItem$.show();
}
$(document).ready(function() {
generateItems();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
To wait for multiple promises, jQuery has the $.when() utility function. Also see this thread and this thread (there are quite a few posts that discuss this, look around).
I've also streamlined your code a bit, I think it's much easier to read this way:
function by(func) {
return function (a, b) {
var aa = func(a), bb = func(b);
return aa < bb ? -1 : aa > bb ? 1 : 0;
};
}
$(function () {
var things = {
'page-header': 'Hello World 1',
'thumbnails': 'It works!',
'nav': 'Great!',
'btn-groups': 'BTN GROUP'
}, requests;
requests = $.map(Object.keys(things), function (key) {
return $.get('https://getbootstrap.com/docs/3.3/components/#/' + key)
.then(function (data) {
return $('<li class="idItem">', {text: things[key] || 'NOT SET!'})[0];
});
});
$.when.apply($, requests).done(function () {
// each argument here is a single <li> element
var items = $(arguments).sort(by(function (el) {
return ($(el).text() || '').toLowerCase();
}));
$('<ul class="allItems">').appendTo('body').append(items);
}).fail(function (jqXhr, status, error) {
// show error
});
});

Waiting for multiple async operations in Nightwatch.js

I am attempting to test multiple sites for section headers being in the correct order. Of course everything is asynchronous in Nightwatch, including getting text from an element. The following code leads to the timeout never being called.
client.url(`www.oneofmyrealestatesites.com`);
client.waitForElementPresent("body", 5000);
var _ = require("underscore");
// This is the order I expect things to be in
var expected = ["Homes For Sale", "New Homes", "Apartments & Rentals"];
client.elements("css selector", ".listings .module-title .label", function (data) {
var listings = [];
data.value.forEach(function (element) {
client.elementIdText(element.ELEMENT, function (result) {
listings.push(result.value);
})
})
setTimeout(function () {
// Some of the sites have extra sections
var diff = _.intersection(listings, expected);
client.assert.ok(listings == diff);
}, 5000);
});
It would appear that no matter how much delay I give, listings is ALWAYS empty. If I console.log listings as it's being pushed to, it is getting populated, so that's not the issue. client.pause is always ignored as well.
Is there a way to make sure that listings is populated before asserting the diff?
I'm using async library for such cases https://github.com/caolan/async
Docs: https://github.com/caolan/async/blob/v1.5.2/README.md
var async = require("async");
/*use each, eachSeries or eachLimit - check docs for differences */
async.eachSeries(data.value, function (element, cb) {
client.elementIdText(element.ELEMENT, function (result) {
listings.push(result.value);
// this job is done
cb();
});
}, function() {
// Some of the sites have extra sections
var diff = _.intersection(listings, expected);
client.assert.ok(listings == diff);
});
setTimeout can only be called from .execute or .executeAsync because its actual javascript. The function below was only working until I used .executeAsync
Hope this works for you.
Cheers, Rody
LoopQuestionsLogSymptom: function() {
this.waitForElementVisible('.next-button', constants.timeout.medium, false);
this.api.executeAsync(function() {
let checkQuestion = function() {
// GET THE ELEMENTS
let nextButton = document.querySelectorAll('.next-button');
let answers = document.getElementsByClassName('flex-row');
let blueButton = document.querySelector('.blue-inverse-button');
let doneButton = document.querySelector('#doneButton');
let monitor = document.querySelector('.monitor');
//CHECK THE TYPES OF QUESTIONS AND CLICK THE RIGHT BUTTONS
if (!blueButton) {
answers[0].click();
nextButton[0].click()
} else if(blueButton){
blueButton.click();
}
setTimeout(() => {
if(!doneButton) {
console.log('Answering another question!');
checkQuestion();
}
if(doneButton){
doneButton.click();
}
else if(monitor) {
console.log("Exiting?")
.assert(monitor);
return this;
}
}, 2000);
};
// Initiating the check question function
return checkQuestion();
},[], function(){
console.log('Done?')
});
this.waitForElementVisible('.monitor', constants.timeout.medium);
this.assert.elementPresent('.monitor');
this.assert.urlEquals('https://member-portal.env-dev4.vivantehealth.org/progress');
return this;
},

Reactive javascript - convert ajax calls to Bacon.js stream with pagination

How can I convert calls to server API, with pagination support, to a Bacon.js / RxJs stream?
For the pagination I want to be able to store the last requested item-index, and ask for the next page_size items from that index to fill the stream.
But I need the 'load next page_size items' method to be called only when all items in stream already been read.
Here is a test that I wrote:
var PAGE_SIZE = 20;
var LAST_ITEM = 100;
var FIRST_ITEM = 0;
function getItemsFromServer(fromIndex) {
if (fromIndex > LAST_ITEM) {
return [];
}
var remainingItemsCount = LAST_ITEM-fromIndex;
if (remainingItemsCount <= PAGE_SIZE) {
return _.range(fromIndex, fromIndex + remainingItemsCount);
}
return _.range(fromIndex, fromIndex + PAGE_SIZE);
}
function makeStream() {
return Bacon.fromBinder(function(sink) {
var fromIndex = FIRST_ITEM;
function loadMoreItems() {
var items = getItemsFromServer(fromIndex);
fromIndex = fromIndex + items.length;
return items;
}
var hasMoreItems = true;
while (hasMoreItems) {
var items = loadMoreItems();
if (items.length < PAGE_SIZE) { hasMoreItems = false; }
_.forEach(items, function(item) { sink(new Bacon.Next(item)); });
}
return function() { console.log('done'); };
});
}
makeStream().onValue(function(value) {
$("#events").append($("<li>").text(value))
});
http://jsfiddle.net/Lc2oua5x/10/
Currently the 'getItemsFromServer' method is only a dummy and generate items locally. How to combine it with ajax call or a promise that return array of items? and can be execute unknown number of times (depends on the number of items on the server and the page size).
I read the documentation regarding Bacon.fromPromise() but couldn't manage to use it along with the pagination.
You need to use flatMap to map pages to streams created with Bacon.fromPromise. Here is a working example, where I use the jsfiddle echo endpoint ( it sends the same data back )
Bacon.sequentially(0, _.range(0,5))
.map(toIndex)
.flatMap(loadFromServer)
.onValue(render)
function toIndex(page) {
return page * PAGE_SIZE
}
function loadFromServer(index) {
var response = getItemsFromServer(index)
return Bacon.fromPromise($.ajax({
type: 'POST',
dataType: 'json',
url: '/echo/json/',
data : { json: JSON.stringify( response ) }
}))
}
function render(items) {
items.forEach(function(item) {
$("#events").append($("<li>").text(item))
})
}
http://jsfiddle.net/1eqec9g3/2/
Note: this code relies on responses coming from the server in the same order they were sent.

How to deal with asyncronous javascript in loops?

I have a forloop like this:
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname);
myphone.get(function(phonenumbers){
if(myphone.phonearray){
myperson.save();
//Can I put a break here?;
}
});
}
What it does is that it searches for phone-numbers in a database based on various first-names. What I want to achieve is that once it finds a number associated with any of the first names, it performs myperson.save and then stops all the iterations, so that no duplicates get saved. Sometimes, none of the names return any phone-numbers.
myphone.get contains a server request and the callback is triggered on success
If I put a break inside the response, what will happen with the other iterations of the loop? Most likely the other http-requests have already been initiated. I don't want them to perform the save. One solution I have thought of is to put a variable outside of the forloop and set it to save, and then check when the other callbacks get's triggered, but I'm not sure if that's the best way to go.
You could write a helper function to restrict invocations:
function callUntilTrue(cb) {
var done = false;
return function () {
if (done) {
log("previous callback succeeded. not calling others.");
return;
}
var res = cb.apply(null, arguments);
done = !! res;
};
}
var myperson = {
firstname: {
"tom": null,
"jerry": null,
"micky": null
},
save: function () {
log("save " + JSON.stringify(this, null, 2));
}
};
var cb = function (myperson_, phonenumbers) {
if (myperson_.phonearray) {
log("person already has phone numbers. returning.");
return false;
}
if (phonenumbers.length < 1) {
log("response has no phone numbers. returning.");
return false;
}
log("person has no existing phone numbers. saving ", phonenumbers);
myperson_.phonearray = phonenumbers;
myperson_.save();
return true;
};
var restrictedCb = callUntilTrue(cb.bind(null, myperson));
for (var name in myperson.firstname) {
var myphone = new phone(myperson, name);
myphone.get(restrictedCb);
}
Sample Console:
results for tom-0 after 1675 ms
response has no phone numbers. returning.
results for jerry-1 after 1943 ms
person has no existing phone numbers. saving , [
"jerry-1-0-number"
]
save {
"firstname": {
"tom": null,
"jerry": null,
"micky": null
},
"phonearray": [
"jerry-1-0-number"
]
}
results for micky-2 after 4440 ms
previous callback succeeded. not calling others.
Full example in this jsfiddle with fake timeouts.
EDIT Added HTML output as well as console.log.
The first result callback will only ever happen after the loop, because of the single-threaded nature of javascript and because running code isn't interrupted if events arrive.
If you you still want requests to happen in parallel, you may use a flag
var saved = false;
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
myphone.get(function(phonenumbers){
if (!saved && myphone.phonearray){
saved = true;
myperson.save();
}
});
}
This will not cancel any pending requests, however, just prevent the save once they return.
It would be better if your .get() would return something cancelable (the request itself, maybe).
var saved = false;
var requests = [];
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
var r;
requests.push(r = myphone.get(function(phonenumbers){
// Remove current request.
requests = requests.filter(function(i) {
return r !== i;
});
if (saved || !myphone.phonearray) {
return;
}
saved = true;
// Kill other pending/unfinished requests.
requests.forEach(function(r) {
 r.abort();
});
myperson.save();
}));
}
Even better, don't start all requests at once. Instead construct an array of all possible combinations, have a counter (a semaphore) and only start X requests.
var saved = false;
var requests = [];
// Use requests.length as the implicit counter.
var waiting = []; // Wait queue.
for (var name in myperson.firstname){
var myphone = new phone(myperson, firstname /* name? */);
var r;
if (requests.length >= 4) {
// Put in wait queue instead.
waiting.push(myphone);
continue;
}
requests.push(r = myphone.get(function cb(phonenumbers){
// Remove current request.
requests = requests.filter(function(i) {
return r !== i;
});
if (saved) {
return;
}
if (!myphone.phonearray) {
// Start next request.
var w = waiting.shift();
if (w) {
requests.push(w.get(cb));
)
return;
}
saved = true;
// Kill other pending/unfinished requests.
requests.forEach(function(r) {
r.abort();
});
myperson.save();
}));
}

Categories

Resources