Having a difficult time understanding callback functions - javascript

I'm new to JavaScript and i'm having difficulties understanding callback functions.
I have a function below that returns an array and then another function that calls the first function. Problem is, the array in the second function is always undefined, even though in the first function is returns an array of objects.
function getItems() {
$.get(url,
function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
return itemArr;
});
}
function alertTest() {
var items = getItems();
alert(items);
}
I understand that the first function is asynchronous and so that the alert in the second function is called before the returned array, which causes the second function to alert an undefined object.
I'm aware there is quite some documentation around this but i'm having trouble understanding how it works. Could someone show me the changes i would need to make so that the alertTest function returns the populated array after the getItems function has been called?
Thanks in advance!

$.get is an async function. which means the callback function is invoked when the is hit and the response is returned inside .
Now return itemArr is actually returned by the callback function and
getItems() doesn't actually return anything and hence it is always undefined.
For your code to work,
function getItems() {
$.get(url,
function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
alertTest(itemArr);
return itemArr;
});
}
this would call alertTest function.

One way to do this would be to use JS Promises like so
function getItems() {
return Promise.resolve(
$.get(url,
function (data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function (ele) {
return ele;
})
return itemArr;
}));
}
function alertTest() {
var items = getItems().then(function (items) {
alert(items);
});
}
It is a hard one to get your head around. Promises allow you to write code that runs in a sequence like sync code.
You could insert callbacks into the function and have that call when the get request finishes like shown in the other answer by Rhea but this is a cleaner way to do this and Promises are now part of the Javascript language.

function getItems() {
$.get(url, function(data) {
var obj = $.parseJSON(data);
var itemArr = $.map(obj, function(ele) { return ele; })
alertTest(itemArr);
});
}
function alertTest(items) {
alert(items);
}
getItems();

Related

I need a way to execute an array of ajax calls wrapped in a function

The system I'm working with was designed to only make synchronous ajax calls, so i am looking for a workaround. First i have an ajax call that is wrapped in a function. I then wrap it in another function so it doesn't get executed when adding it to the array. So i have two arrays of async ajax call functions. I would like to execute everything in the first array, and then wait until everything has completed. I would then like to execute everything in a second array. This is what i have so far
I have a loop that goes through items and I have a wrap function for each item that takes in my already wrapped ajax call so that it doesn't get executed and stores it in an array like below
var postpromises = [];
var WrapFunction = function (fn, context, params) {
return function () {
fn.apply(context, params);
};
}
var postPromise = WrapFunction(ajaxFunction, this, [{
url: url,
data: j,
async: true,
type: 'POST',
success: function (data) {
//success
},
error: function (xhr, textStatus, errorThrown) {
//error
}
}]);
postpromises.push(postPromise);
I then have the same code for validation. So before I move on to next page, I have the following
$.when.apply(undefined, postpromises).then(function () {
console.log();
$.when.apply(undefined, validatepromises).then(function () {
console.log();
});
});
The issue is that when I get to the code above, none of my postpromises even get executed, so I feel like I may be missing something here.
Ideas?
The function $.when require a promise, in your code you are returning a function that return nothing, so just return the result of the wrapped function:
ES6 spread operator REF
function arguments object REF
var postpromises = [];
var validatepromises = [];
function f1() {
var fakePromise = $.Deferred();
setTimeout(() => {
fakePromise.resolve("IM RESOLVED!!");
}, 500);
return fakePromise.promise();
}
//OLD ONE
/*var WrapFunction = function (fn, context, params) {
return function () {
fn.apply(context, params);
};
}*/
var WrapFunction = function(fn, context, params) {
return function() {
return fn.apply(context, params);
}();
}
var postPromise = WrapFunction(f1, this, []);
postpromises = [postPromise];
var validatePromise = WrapFunction(f1, this, []);
validatepromises = [validatePromise];
//OLD ONE
/*$.when.apply(undefined, postpromises).then(function(res) {
console.log(res);
$.when.apply(undefined, validatepromises).then(function(res) {
console.log(res);
});
});*/
$.when.apply(null, [...postpromises, ...validatepromises]).then(function() {
console.log([].slice.call(arguments))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

get element attribute value in Protractor

I'm writing a Protractor test that has to wait for an element attribute to have a non-empty value and then I want to return that value to the caller function. This has proven to be more difficult to write than I expected!
I am able to correctly schedule a browser.wait() command to wait for the element attribute to have a non-empty value and I have verified that this value is in fact what I am expecting to get inside the callback function, but for some reason, I am not able to return that value outside of the callback function and onto the rest of the test code.
Here is how my code looks like:
function test() {
var item = getItem();
console.log(item);
}
function getItem() {
var item;
browser.wait(function() {
return element(by.id('element-id')).getAttribute('attribute-name').then(function(value) {
item = value;
// console.log(item);
return value !== '';
});
});
return item;
}
I can tell that the order of execution is not as I expect it to be, because when I uncomment the console.log() call inside the callback function, I see the expected value printed out. However, the same call in the test() function prints 'undefined'.
What is going on here? What am I missing? How can I get the attribute value out of the callback function properly?
I appreciate your help.
I would not combine the wait and the getting attribute parts - logically these are two separate things, keep them separate:
browser.wait(function() {
return element(by.id('element-id')).getAttribute("attribute").then(function(value) {
item = value;
// console.log(item);
return value !== '';
});
});
element(by.id('element-id')).getAttribute("attribute").then(function (value) {
console.log(value);
});
Note that, you may simplify the wait condition this way:
var EC = protractor.ExpectedConditions;
var elm = $('#element-id[attribute="expected value"]');
browser.wait(EC.presenceOf(elm), 5000);
elm.getAttribute("attribute").then(function (value) {
console.log(value);
});
Just FYI, you may have solved your current problem with the deferred:
function test() {
getItem().then(function (value) {
console.log(value);
});
}
function getItem() {
var item = protractor.promise.defer();
browser.wait(function() {
return element(by.id('element-id')).getAttribute('attribute').then(function(value) {
var result = value !== '';
if (result) {
item.fulfill(value);
}
return result;
});
});
return item.promise;
}
After doing some more reading about how protractor works with promises and schedules/registers them with the control flow, I found an easier work-around close to the first solution #alecxe provided. Here it goes:
function test() {
var item = getItem().then(function(item) {
console.log(item);
});
}
function getItem() {
return browser.wait(function() {
return element(by.id('element-id')).getAttribute('attribute-name').then(function(value) {
return value;
});
});
}
Since browser.wait() returns a promise itself, it can be chained with another then() inside the caller and this way the right order of execution is guaranteed.

angular controller function does not return results from one function to another

in my controller i have a function
$scope.orderHistory = {};
$scope.results = {};
var getHistory = function (max,offset)
{
//do some stuff
$scope.orderHistory = data.entities;
angular.forEach($scope.orderHistory,function(value)
{
$scope.results = getResults(value.id);
console.log($scope.results);
});
}
var getResults = function(id)
{
api.getHistoryData(id)
.then ( function (results)
{
return results.data;
});
};
the problem i run into is the getResults function does not seem to actually return the data and have it set to $scope.results inside the getHistory function.
When i do a console.log in (results.data) inside the .then part of getResults function i see the results. Can anyone help me understand why it is not returning the results even though it exists and what i can do to fix it
The function in then(function(){...}) is executed asynchronously, and the containing getResults function won't wait for it to return. More specifically, api.getHistoryData seems to return a promise.
You can use Angular's data binding to work around this:
var getHistory = function (max,offset)
{
//do some stuff
$scope.orderHistory = data.entities;
angular.forEach($scope.orderHistory,function(value)
{
getResults(value.id);
});
}
var getResults = function(id)
{
api.getHistoryData(id)
.then ( function (results) {
$scope.results = results.data;
});
};
And then in your template use something like:
<button ng-click="getHistory(0, 0)"></button>
{{results}}
Lets see if I can clarify how promises work, and what might be throwing you off here:
When you say:
$scope.results = getResults(value.id);
That means, assign the return value of getResults to the $scope.results variable. Now let us take a look at your getResults function.
var getResults = function(id) {
api.getHistoryData(id)
.then(function (results) {
return results.data;
});
};
Now notice a few things:
The getResults function does not have a return statement. That means there is nothing returned from getResults to be assigned to $scope.results.
The getResults function itself makes an asynchronous request. That means, if when the function executes, and when the results come back are two different points in time.
Finally, your return statement is not inside the getResults function (technically it is), but is in fact inside a function inside the getResults function. Thus, the return results.data is for the function(results) {} and not for getResults
Also, notice if it had worked as you would have expected it to, you would keep overriding the value of $scope.results each time the server responded. That's probably not what you want
Let us modify the getResults function to clarify this:
angular.forEach($scope.orderHistory, function(value) {
console.log('1 - Get results for ', value.id);
getResults(value.id);
});
var getResults = function(id) {
console.log('2 - GetResults called');
api.getHistoryData(id)
.then(function (results) {
console.log('3 - Get results has data');
return results.data;
});
};
If we had code like the above, then the console.logs for 1 and 2 would get printed first, all together, and then at some later point, all the 3's would get printed together. This is because JavaScript is asynchronous and non-blocking, which means it will continue executing without waiting for the responses to come back.
So instead, to get this to work like you expect it to, you need to leverage Promises in AngularJS, which allow you a hook to know when the server response has come back. It offers us a way of working with asynchronous events across functions. So if you modify your code as follows:
angular.forEach($scope.orderHistory, function(value) {
getResults(value.id).then(function(results) {
$scope.results[value.id] = results.data;
});
});
var getResults = function(id) {
return api.getHistoryData(id);
};
So we return a promise from getResults, and then when the promise is completed, we use the value and set it on $scope.results in the main function.
Hope this makes things clearer.
I think you aren't using the promise correctly:
$scope.orderHistory = {};
$scope.results = {};
var getHistory = function (max,offset)
{
//do some stuff
$scope.orderHistory = data.entities;
angular.forEach($scope.orderHistory,function(value)
{
// get results returns a promise
// we use the promise to set $scope.results
getResults(value.id).then(function(results){
$scope.results = results.data;
});
});
}
// returns a promise
var getResults = function(id)
{
return api.getHistoryData(id);
};
$scope.results will be changed only after the promise is resolved.
Also, the way it is currently written, $scope.results will be overwritten for each value.id. If that is not your intention I'd turn it into an array and push each new value into it.
Lets be clear, your orderHistory and results variables are objects, not arrays. The angular.forEach function allows you to iterate over both arrays and object properties; it does not mean the object being iterated is an array. Elad is correct in stating that your results variable will be overwritten for each iteration.
If you do want to keep all the results from your getResults function, you need to instantiate results as an array; and to have your view reflect the results, push them into your scope variable directly from the async result.
$scope.orderHistory = {};
$scope.results = [];
var getHistory = function (max,offset)
{
//do some stuff
$scope.orderHistory = data.entities;
angular.forEach($scope.orderHistory,function(value)
{
getResults(value.id);
});
}
var getResults = function(id)
{
api.getHistoryData(id)
.then ( function (results)
{
$scope.results.push(results);
});
};
just fix getResults, add return to it
var getResults = function(id)
{
return api.getHistoryData(id)
.then ( function (results)
{
return results.data;
});
};
Here are 2 points.
First, getResults returns nothing, it just process chain of promisses. We can change getResults to return promiss which will return result:
var getResults = function(id)
{
return api.getHistoryData(id)
.then ( function (results)
{
return results.data;
});
};
Second, from angular version 1.2 (not exactly sure if from this version) angular do not resolve promisses automaticaly so you must to do it yourself:
angular.forEach($scope.orderHistory,function(value)
{
getResults(value.id).then(function(results){
$scope.results = results;
console.log($scope.results);
})
});
The whole code:
$scope.orderHistory = {};
$scope.results = {};
var getHistory = function (max,offset)
{
//do some stuff
$scope.orderHistory = data.entities;
angular.forEach($scope.orderHistory,function(value)
{
getResults(value.id).then(function(results){
$scope.results = results;
console.log($scope.results);
})
});
}
// returns a promise
var getResults = function(id)
{
return api.getHistoryData(id)
.then ( function (results)
{
return results.data;
});
};

jQuery Promise, $.when execute all deferreds in array [duplicate]

Here's an contrived example of what's going on: http://jsfiddle.net/adamjford/YNGcm/20/
HTML:
Click me!
<div></div>
JavaScript:
function getSomeDeferredStuff() {
var deferreds = [];
var i = 1;
for (i = 1; i <= 10; i++) {
var count = i;
deferreds.push(
$.post('/echo/html/', {
html: "<p>Task #" + count + " complete.",
delay: count
}).success(function(data) {
$("div").append(data);
}));
}
return deferreds;
}
$(function() {
$("a").click(function() {
var deferreds = getSomeDeferredStuff();
$.when(deferreds).done(function() {
$("div").append("<p>All done!</p>");
});
});
});
I want "All done!" to appear after all of the deferred tasks have completed, but $.when() doesn't appear to know how to handle an array of Deferred objects. "All done!" is happening first because the array is not a Deferred object, so jQuery goes ahead and assumes it's just done.
I know one could pass the objects into the function like $.when(deferred1, deferred2, ..., deferredX) but it's unknown how many Deferred objects there will be at execution in the actual problem I'm trying to solve.
To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:
$.when.apply($, my_array).then( ___ );
See http://jsfiddle.net/YNGcm/21/
In ES6, you can use the ... spread operator instead:
$.when(...my_array).then( ___ );
In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.
The workarounds above (thanks!) don't properly address the problem of getting back the objects provided to the deferred's resolve() method because jQuery calls the done() and fail() callbacks with individual parameters, not an array. That means we have to use the arguments pseudo-array to get all the resolved/rejected objects returned by the array of deferreds, which is ugly:
$.when.apply($,deferreds).then(function() {
var objects = arguments; // The array of resolved objects as a pseudo-array
...
};
Since we passed in an array of deferreds, it would be nice to get back an array of results. It would also be nice to get back an actual array instead of a pseudo-array so we can use methods like Array.sort().
Here is a solution inspired by when.js's when.all() method that addresses these problems:
// Put somewhere in your scripting environment
if (typeof jQuery.when.all === 'undefined') {
jQuery.when.all = function (deferreds) {
return $.Deferred(function (def) {
$.when.apply(jQuery, deferreds).then(
// the calling function will receive an array of length N, where N is the number of
// deferred objects passed to when.all that succeeded. each element in that array will
// itself be an array of 3 objects, corresponding to the arguments passed to jqXHR.done:
// ( data, textStatus, jqXHR )
function () {
var arrayThis, arrayArguments;
if (Array.isArray(this)) {
arrayThis = this;
arrayArguments = arguments;
}
else {
arrayThis = [this];
arrayArguments = [arguments];
}
def.resolveWith(arrayThis, [Array.prototype.slice.call(arrayArguments)]);
},
// the calling function will receive an array of length N, where N is the number of
// deferred objects passed to when.all that failed. each element in that array will
// itself be an array of 3 objects, corresponding to the arguments passed to jqXHR.fail:
// ( jqXHR, textStatus, errorThrown )
function () {
var arrayThis, arrayArguments;
if (Array.isArray(this)) {
arrayThis = this;
arrayArguments = arguments;
}
else {
arrayThis = [this];
arrayArguments = [arguments];
}
def.rejectWith(arrayThis, [Array.prototype.slice.call(arrayArguments)]);
});
});
}
}
Now you can simply pass in an array of deferreds/promises and get back an array of resolved/rejected objects in your callback, like so:
$.when.all(deferreds).then(function(objects) {
console.log("Resolved objects:", objects);
});
You can apply the when method to your array:
var arr = [ /* Deferred objects */ ];
$.when.apply($, arr);
How do you work with an array of jQuery Deferreds?
When calling multiple parallel AJAX calls, you have two options for handling the respective responses.
Use Synchronous AJAX call/ one after another/ not recommended
Use Promises' array and $.when which accepts promises and its callback .done gets called when all the promises are return successfully with respective responses.
Example
function ajaxRequest(capitalCity) {
return $.ajax({
url: 'https://restcountries.eu/rest/v1/capital/'+capitalCity,
success: function(response) {
},
error: function(response) {
console.log("Error")
}
});
}
$(function(){
var capitalCities = ['Delhi', 'Beijing', 'Washington', 'Tokyo', 'London'];
$('#capitals').text(capitalCities);
function getCountryCapitals(){ //do multiple parallel ajax requests
var promises = [];
for(var i=0,l=capitalCities.length; i<l; i++){
var promise = ajaxRequest(capitalCities[i]);
promises.push(promise);
}
$.when.apply($, promises)
.done(fillCountryCapitals);
}
function fillCountryCapitals(){
var countries = [];
var responses = arguments;
for(i in responses){
console.dir(responses[i]);
countries.push(responses[i][0][0].nativeName)
}
$('#countries').text(countries);
}
getCountryCapitals()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h4>Capital Cities : </h4> <span id="capitals"></span>
<h4>Respective Country's Native Names : </h4> <span id="countries"></span>
</div>
As a simple alternative, that does not require $.when.apply or an array, you can use the following pattern to generate a single promise for multiple parallel promises:
promise = $.when(promise, anotherPromise);
e.g.
function GetSomeDeferredStuff() {
// Start with an empty resolved promise (or undefined does the same!)
var promise;
var i = 1;
for (i = 1; i <= 5; i++) {
var count = i;
promise = $.when(promise,
$.ajax({
type: "POST",
url: '/echo/html/',
data: {
html: "<p>Task #" + count + " complete.",
delay: count / 2
},
success: function (data) {
$("div").append(data);
}
}));
}
return promise;
}
$(function () {
$("a").click(function () {
var promise = GetSomeDeferredStuff();
promise.then(function () {
$("div").append("<p>All done!</p>");
});
});
});
Notes:
I figured this one out after seeing someone chain promises sequentially, using promise = promise.then(newpromise)
The downside is it creates extra promise objects behind the scenes and any parameters passed at the end are not very useful (as they are nested inside additional objects). For what you want though it is short and simple.
The upside is it requires no array or array management.
I want to propose other one with using $.each:
We may to declare ajax function like:
function ajaxFn(someData) {
this.someData = someData;
var that = this;
return function () {
var promise = $.Deferred();
$.ajax({
method: "POST",
url: "url",
data: that.someData,
success: function(data) {
promise.resolve(data);
},
error: function(data) {
promise.reject(data);
}
})
return promise;
}
}
Part of code where we creating array of functions with ajax to send:
var arrayOfFn = [];
for (var i = 0; i < someDataArray.length; i++) {
var ajaxFnForArray = new ajaxFn(someDataArray[i]);
arrayOfFn.push(ajaxFnForArray);
}
And calling functions with sending ajax:
$.when(
$.each(arrayOfFn, function(index, value) {
value.call()
})
).then(function() {
alert("Cheer!");
}
)
If you're transpiling and have access to ES6, you can use spread syntax which specifically applies each iterable item of an object as a discrete argument, just the way $.when() needs it.
$.when(...deferreds).done(() => {
// do stuff
});
MDN Link - Spread Syntax
I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.
Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.
// 1st
function Outer() {
var deferreds = GetAllData();
$.when.apply($, deferreds).done(function () {
// now you can do whatever you want with the updated page
});
}
// 2nd
function GetAllData() {
var deferreds = [];
$('.calculatedField').each(function (data) {
deferreds.push(GetIndividualData($(this)));
});
return deferreds;
}
// 3rd
function GetIndividualData(item) {
var def = new $.Deferred();
$.post('#Url.Action("GetData")', function (data) {
item.html(data.valueFromAjax);
def.resolve(data);
});
return def;
}
If you're using angularJS or some variant of the Q promise library, then you have a .all() method that solves this exact problem.
var savePromises = [];
angular.forEach(models, function(model){
savePromises.push(
model.saveToServer()
)
});
$q.all(savePromises).then(
function success(results){...},
function failed(results){...}
);
see the full API:
https://github.com/kriskowal/q/wiki/API-Reference#promiseall
https://docs.angularjs.org/api/ng/service/$q

Pass or return JSON Object from jQuery GET

I have a function that makes a GET request for a nested JSON object. The object is returned successfully but you can't access the other objects within the returned object.
the object looks like this :
{
"student": {
"hobbies": ["reading", "dancing", "music"],
"subjects": ["english", "maths", "science"]
}
}
and this is the function :
var superObject = {
getData: function(obj) {
$.get(obj.target, function(callbackObject) {
// It works fine if i log callbackObject
// console.log(callbackObject);
return callbackObject;
}
},
useData: function() {
var data = superObject.getData({'target': 'file.json'});
var hobbies = data.student.hobbies;
console.log(hobbies); // This fails and returns nothing.
}
}
Due to asynchronous Ajax behaviour, you need to pass a callback function to execute once the data retrieved via Ajax is available; something like:
getData: function(obj, callback) {
$.get(obj.target, function(callbackObject) {
callback.call(null, callbackObject);
}
}
useData: function() {
superObject.getData({'target': 'file.json'}, function(data) {
var hobbies = data.student.hobbies;
});
}
The problem is that you're returning callbackObject from your $.get callback, and not from your getData function. $.get is asynchronous, so its callback will not fire until long after getData() has finished. That's why you're seeing undefined.
What about something like:
var superObject = {
getReuslts: {},
getData: function(obj) {
$.get(obj.target, function(callbackObject) {
getReuslts = callbackObject;
this.useData();
}
},
useData: function() {
var hobbies = getReuslts.student.hobbies;
console.log(hobbies);
}
}
Of course this would create a temporal dependency between useData and getData. Why not create this object in a function so you can add some encapsulation?
funcition getSuperObject = {
var result = {};
var getReuslts = {};
function useData() {
var hobbies = getReuslts.student.hobbies;
console.log(hobbies);
}
result.getData = function(obj) {
$.get(obj.target, function(callbackObject) {
getReuslts = callbackObject;
useData();
});
};
return result;
}
Or supply your own callback:
var superObject = {
getData: function(obj, callback) {
$.get(obj.target, function(callbackObject) {
if (callback)
callback(calbackObject);
});
}
}
And then
superObject.getData({'target': 'file.json'}, function(result) {
var hobbies = result.student.hobbies;
console.log(hobbies); // This fails and returns nothing.
});
$.get works asynchronously: you call it, then the browser goes off to make the request. Meanwhile, your code continues running. When the browser gets the response from the server, it invokes the callback function you provided passing it the results.
This means that when getData runs, it will return "almost immediately" and the request started by $.get will still be in progress in the background. So, getData cannot return anything meaningful to its caller because it can only schedule a requestl; it cannot know what the result will end up being.
So it follows that you cannot call getData like this:
var data = superObject.getData({'target': 'file.json'});
What you need to do instead is put the code that depends on the response inside the callback:
$.get(obj.target, function(data) {
var hobbies = data.student.hobbies;
console.log(hobbies); // This will now work
}
The scope of your variables is only in your function
You can try to set the variable hobbies out of your structure, and set it's value inside of your function
var hobbies; //global scope
var superObject = {
getData: function(obj) {
$.get(obj.target, function(callbackObject) {
// It works fine if i log callbackObject
// console.log(callbackObject);
return callbackObject;
}},
useData: function() {
var data = superObject.getData({'target': 'file.json'});
hobbies= data.student.hobbies;
//set it's value
}
}
You are returning in the callback handler. So your result is sent to the callback dispatcher which drops your result. What you need to do is attach your processing code to the get callback:
getData: function(obj) { return $.getJSON(obj.target); },
useData: function() {
getData({ target : 'file.json'}).then(function(results) {
var hobbies = results.student.hobbies;
console.log(hobbies);
}
}
You could turn your asynchronous AJAX call to be synchronous. See http://api.jquery.com/jQuery.ajax/, mainly the "async" option.
See this discussion:
Ajax jquery synchronous callback success

Categories