javascript - How to return the response from an asynchronous call
I have a function foo
which makes an asynchronous request. How can I return the response/result from foo
?
I am trying to return the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response (they all return undefined
or whatever the initial value of the variable result
is).
Example of an asynchronous function that accepts a callback (using jQuery's ajax
function)
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result; // It always returns `undefined`
}
Example using Node.js:
function foo() {
var result;
fs.readFile("path/to/file", function(err, data) {
result = data;
// return data; // <- I tried that one as well
});
return result; // It always returns `undefined`
}
Example using the then
block of a promise:
function foo() {
var result;
fetch(url).then(function(response) {
result = response;
// return response; // <- I tried that one as well
});
return result; // It always returns `undefined`
}
Answer
Solution:
?�� For a more general explanation of asynchronous behaviour with different examples, see Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
?�� If you already understand the problem, skip to the possible solutions below.
The problem
The A in Ajax stands for . That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $.ajax
returns immediately and the next statement, return result;
, is executed before the function you passed as success
callback was even called.
Here is an analogy which hopefully makes the difference between synchronous and asynchronous flow clearer:
Synchronous
Imagine you make a phone call to a friend and ask him to look something up for you. Although it might take a while, you wait on the phone and stare into space, until your friend gives you the answer that you needed.
The same is happening when you make a function call containing "normal" code:
function findItem() {
var item;
while(item_not_found) {
// search
}
return item;
}
var item = findItem();
// Do something with item
doSomethingElse();
Even though findItem
might take a long time to execute, any code coming after var item = findItem();
has to wait until the function returns the result.
Asynchronous
You call your friend again for the same reason. But this time you tell him that you are in a hurry and he should call you back on your mobile phone. You hang up, leave the house, and do whatever you planned to do. Once your friend calls you back, you are dealing with the information he gave to you.
That's exactly what's happening when you do an Ajax request.
findItem(function(item) {
// Do something with the item
});
doSomethingElse();
Instead of waiting for the response, the execution continues immediately and the statement after the Ajax call is executed. To get the response eventually, you provide a function to be called once the response was received, a callback (notice something? call back ?). Any statement coming after that call is executed before the callback is called.
Solution(s)
Embrace the asynchronous nature of JavaScript! While certain asynchronous operations provide synchronous counterparts (so does "Ajax"), it's generally discouraged to use them, especially in a browser context.
Why is it bad do you ask?
JavaScript runs in the UI thread of the browser and any long-running process will lock the UI, making it unresponsive. Additionally, there is an upper limit on the execution time for JavaScript and the browser will ask the user whether to continue the execution or not.
All of this results in a really bad user experience. The user won't be able to tell whether everything is working fine or not. Furthermore, the effect will be worse for users with a slow connection.
In the following we will look at three different solutions that are all building on top of each other:
- Promises with
async/await
(ES2017+, available in older browsers if you use a transpiler or regenerator) - Callbacks (popular in node)
- Promises with
then()
(ES2015+, available in older browsers if you use one of the many promise libraries)
All three are available in current browsers, and node 7+.
ES2017+: Promises with
The ECMAScript version released in 2017 introduced syntax-level support for asynchronous functions. With the help of async
and await
, you can write asynchronous in a "synchronous style". The code is still asynchronous, but it's easier to read/understand.
async/await
builds on top of promises: an async
function always returns a promise. await
"unwraps" a promise and either result in the value the promise was resolved with or throws an error if the promise was rejected.
Important: You can only use await
inside an async
function or in a JavaScript module. Top-level await
is not supported outside of modules, so you might have to make an async IIFE (Immediately Invoked Function Expression) to start an async
context if not using a module.
You can read more about and
on MDN.
Here is an example that elaborates the delay function findItem()
above:
// Using 'superagent' which will return a promise.
var superagent = require('superagent')
// This is isn't declared as `async` because it already returns a promise
function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}
async function getAllBooks() {
try {
// GET a list of book IDs of the current user
var bookIDs = await superagent.get('/user/books');
// wait for 3 seconds (just for the sake of this example)
await delay();
// GET information about each book
return superagent.get('/books/ids='+JSON.stringify(bookIDs));
} catch(error) {
// If any of the awaited promises was rejected, this catch block
// would catch the rejection reason
return null;
}
}
// Start an IIFE to use `await` at the top level
(async function(){
let books = await getAllBooks();
console.log(books);
})();
Current browser and node versions support async/await
. You can also support older environments by transforming your code to ES5 with the help of regenerator (or tools that use regenerator, such as Babel).
Let functions accept callbacks
A callback is when function 1 is passed to function 2. Function 2 can call function 1 whenever it is ready. In the context of an asynchronous process, the callback will be called whenever the asynchronous process is done. Usually, the result is passed to the callback.
In the example of the question, you can make foo
accept a callback and use it as success
callback. So this
var result = foo();
// Code that depends on 'result'
becomes
foo(function(result) {
// Code that depends on 'result'
});
Here we defined the function "inline" but you can pass any function reference:
function myCallback(result) {
// Code that depends on 'result'
}
foo(myCallback);
foo
itself is defined as follows:
function foo(callback) {
$.ajax({
// ...
success: callback
});
}
callback
will refer to the function we pass to foo
when we call it and we pass it on to success
. I.e. once the Ajax request is successful, $.ajax
will call callback
and pass the response to the callback (which can be referred to with result
, since this is how we defined the callback).
You can also process the response before passing it to the callback:
function foo(callback) {
$.ajax({
// ...
success: function(response) {
// For example, filter the response
callback(filtered_response);
}
});
}
It's easier to write code using callbacks than it may seem. After all, JavaScript in the browser is heavily event-driven (DOM events). Receiving the Ajax response is nothing else but an event. Difficulties could arise when you have to work with third-party code, but most problems can be solved by just thinking through the application flow.
ES2015+: Promises with then()
The Promise API is a new feature of ECMAScript 6 (ES2015), but it has good browser support already. There are also many libraries which implement the standard Promises API and provide additional methods to ease the use and composition of asynchronous functions (e.g., bluebird).
Promises are containers for future values. When the promise receives the value (it is resolved) or when it is canceled (rejected), it notifies all of its "listeners" who want to access this value.
The advantage over plain callbacks is that they allow you to decouple your code and they are easier to compose.
Here is an example of using a promise:
function delay() {
// `delay` returns a promise
return new Promise(function(resolve, reject) {
// Only `delay` is able to resolve or reject the promise
setTimeout(function() {
resolve(42); // After 3 seconds, resolve the promise with value 42
}, 3000);
});
}
delay()
.then(function(v) { // `delay` returns a promise
console.log(v); // Log the value once it is resolved
})
.catch(function(v) {
// Or do something else if it is rejected
// (it would not happen in this example, since `reject` is not called).
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
Answer
Solution:
If you're not using jQuery in your code, this answer is for you
Your code should be something along the lines of this:
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/echo/json");
httpRequest.send();
return httpRequest.responseText;
}
var result = foo(); // Always ends up being 'undefined'
Felix Kling did a fine job writing an answer for people using jQuery for AJAX, but I've decided to provide an alternative for people who aren't.
(Note, for those using the new fetch
API, Angular or promises I've added another answer below)
What you're facing
This is a short summary of "Explanation of the problem" from the other answer, if you're not sure after reading this, read that.
The A in AJAX stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, .send
returns immediately and the next statement, return result;
, is executed before the function you passed as success
callback was even called.
This means when you're returning, the listener you've defined did not execute yet, which means the value you're returning has not been defined.
Here is a simple analogy:
function getFive(){
var a;
setTimeout(function(){
a=5;
},10);
return a;
}
The value of a
returned is undefined
since the a=5
part has not executed yet. AJAX acts like this, you're returning the value before the server got the chance to tell your browser what that value is.
One possible solution to this problem is to code re-actively , telling your program what to do when the calculation completed.
function onComplete(a){ // When the code completes, do this
alert(a);
}
function getFive(whenDone){
var a;
setTimeout(function(){
a=5;
whenDone(a);
},10);
}
This is called CPS. Basically, we're passing getFive
an action to perform when it completes, we're telling our code how to react when an event completes (like our AJAX call, or in this case the timeout).
Usage would be:
getFive(onComplete);
Which should alert "5" to the screen. (Fiddle).
Possible solutions
There are basically two ways how to solve this:
- Make the AJAX call synchronous (let??�s call it SJAX).
- Restructure your code to work properly with callbacks.
1. Synchronous AJAX - Don't do it!!
As for synchronous AJAX, don't do it! Felix's answer raises some compelling arguments about why it's a bad idea. To sum it up, it'll freeze the user's browser until the server returns the response and create a very bad user experience. Here is another short summary taken from MDN on why:
XMLHttpRequest supports both synchronous and asynchronous communications. In general, however, asynchronous requests should be preferred to synchronous requests for performance reasons.
In short, synchronous requests block the execution of code... ...this can cause serious issues...
If you have to do it, you can pass a flag. Here is how:
var request = new XMLHttpRequest();
request.open('GET', 'yourURL', false); // `false` makes the request synchronous
request.send(null);
if (request.status === 200) {// That's HTTP for 'ok'
console.log(request.responseText);
}
2. Restructure code
Let your function accept a callback. In the example code foo
can be made to accept a callback. We'll be telling our code how to react when foo
completes.
So:
var result = foo();
// Code that depends on `result` goes here
Becomes:
foo(function(result) {
// Code that depends on `result`
});
Here we passed an anonymous function, but we could just as easily pass a reference to an existing function, making it look like:
function myHandler(result) {
// Code that depends on `result`
}
foo(myHandler);
For more details on how this sort of callback design is done, check Felix's answer.
Now, let's define foo itself to act accordingly
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function(){ // When the request is loaded
callback(httpRequest.responseText);// We're calling our method
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
}
We have now made our foo function accept an action to run when the AJAX completes successfully. We can extend this further by checking if the response status is not 200 and acting accordingly (create a fail handler and such). Effectively it is solving our issue.
If you're still having a hard time understanding this, read the AJAX getting started guide at MDN.
Answer
Solution:
XMLHttpRequest 2 (first of all, read the answers from Benjamin Gruenbaum and Felix Kling)
If you don't use jQuery and want a nice short XMLHttpRequest 2 which works in the modern browsers and also in the mobile browsers, I suggest to use it this way:
function ajax(a, b, c){ // URL, callback, just a placeholder
c = new XMLHttpRequest;
c.open('GET', a);
c.onload = b;
c.send()
}
As you can see:
- It's shorter than all other functions Listed.
- The callback is set directly (so no extra unnecessary closures).
- It uses the new onload (so you don't have to check for readystate && status)
- There are some other situations, which I don't remember, that make the XMLHttpRequest 1 annoying.
There are two ways to get the response of this Ajax call (three using the XMLHttpRequest var name):
The simplest:
this.response
Or if for some reason you bind()
the callback to a class:
e.target.response
Example:
function callback(e){
console.log(this.response);
}
ajax('URL', callback);
Or (the above one is better anonymous functions are always a problem):
ajax('URL', function(e){console.log(this.response)});
Nothing easier.
Now some people will probably say that it's better to use onreadystatechange or the even the XMLHttpRequest variable name. That's wrong.
Check out XMLHttpRequest advanced features.
It supported all *modern browsers. And I can confirm as I have been using this approach since XMLHttpRequest 2 was created. I never had any type of problem in any browsers I used.
onreadystatechange is only useful if you want to get the headers on state 2.
Using the XMLHttpRequest
variable name is another big error as you need to execute the callback inside the onload/oreadystatechange closures, or else you lost it.
Now if you want something more complex using POST and FormData you can easily extend this function:
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val},placeholder
c = new XMLHttpRequest;
c.open(e||'get', a);
c.onload = b;
c.send(d||null)
}
Again ... it's a very short function, but it does GET and POST.
Examples of usage:
x(url, callback); // By default it's GET so no need to set
x(url, callback, 'post', {'key': 'val'}); // No need to set POST data
Or pass a full form element (document.getElementsByTagName('form')[0]
):
var fd = new FormData(form);
x(url, callback, 'post', fd);
Or set some custom values:
var fd = new FormData();
fd.append('key', 'val')
x(url, callback, 'post', fd);
As you can see, I didn't implement sync... it's a bad thing.
Having said that ... why don't we do it the easy way?
As mentioned in the comment, the use of error && synchronous does completely break the point of the answer. Which is a nice short way to use Ajax in the proper way?
Error handler
function x(a, b, e, d, c){ // URL, callback, method, formdata or {key:val}, placeholder
c = new XMLHttpRequest;
c.open(e||'get', a);
c.onload = b;
c.onerror = error;
c.send(d||null)
}
function error(e){
console.log('--Error--', this.type);
console.log('this: ', this);
console.log('Event: ', e)
}
function displayAjax(e){
console.log(e, this);
}
x('WRONGURL', displayAjax);
In the above script, you have an error handler which is statically defined, so it does not compromise the function. The error handler can be used for other functions too.
But to really get out an error, the only way is to write a wrong URL in which case every browser throws an error.
Error handlers are maybe useful if you set custom headers, set the responseType to blob array buffer, or whatever...
Even if you pass 'POSTAPAPAP' as the method it won't throw an error.
Even if you pass 'fdggdgilfdghfldj' as formdata it won't throw an error.
In the first case the error is inside the displayAjax()
under this.statusText
as Method not Allowed
.
In the second case, it simply works. You have to check at the server side if you passed the right post data.
Cross-domain not allowed throws an error automatically.
In the error response, there aren't any error codes.
There is only the this.type
which is set to error.
Why add an error handler if you totally don't have any control over errors?
Most of the errors are returned inside this in the callback function displayAjax()
.
So: There isn't any need for error checks if you're able to copy and paste the URL properly. ;)
PS: As the first test I wrote x('x', displayAjax)..., and it totally got a response...??? So I checked the folder where the HTML is located, and there was a file called 'x.xml'. So even if you forget the extension of your file XMLHttpRequest 2 WILL FIND IT. I LOL'd
Read a file synchronous
Don't do that.
If you want to block the browser for a while load a nice big .txt
file synchronous.
function omg(a, c){ // URL
c = new XMLHttpRequest;
c.open('GET', a, true);
c.send();
return c; // Or c.response
}
Now you can do
var res = omg('thisIsGonnaBlockThePage.txt');
There is no other way to do this in a non-asynchronous way. (Yeah, with setTimeout loop... but seriously?)
Another point is... if you work with APIs or just your own list's files or whatever you always use different functions for each request...
Only if you have a page where you load always the same XML/JSON or whatever you need only one function. In that case, modify a little the Ajax function and replace b with your special function.
The functions above are for basic use.
If you want to extend the function...
Yes, you can.
I'm using a lot of APIs and one of the first functions I integrate into every HTML page is the first Ajax function in this answer, with GET only...
But you can do a lot of stuff with XMLHttpRequest 2:
I made a download manager (using ranges on both sides with resume, filereader, and filesystem), various image resizers converters using canvas, populate web SQL databases with base64images and much more...
But in these cases you should create a function only for that purpose... sometimes you need a blob, array buffers, you can set headers, override mimetype and there is a lot more...
But the question here is how to return an Ajax response... (I added an easy way.)
Answer
Solution:
If you're using promises, this answer is for you.
This means AngularJS, jQuery (with deferred), native XHR's replacement (fetch), Ember.js, Backbone.js's save or any Node.js library that returns promises.
Your code should be something along the lines of this:
function foo() {
var data;
// Or $.get(...).then, or request(...).then, or query(...).then
fetch("/echo/json").then(function(response){
data = response.json();
});
return data;
}
var result = foo(); // 'result' is always undefined no matter what.
Felix Kling did a fine job writing an answer for people using jQuery with callbacks for Ajax. I have an answer for native XHR. This answer is for generic usage of promises either on the frontend or backend.
The core issue
The JavaScript concurrency model in the browser and on the server with Node.js/io.js is asynchronous and reactive.
Whenever you call a method that returns a promise, the then
handlers are always executed asynchronously - that is, after the code below them that is not in a .then
handler.
This means when you're returning data
the then
handler you've defined did not execute yet. This in turn means that the value you're returning has not been set to the correct value in time.
Here is a simple analogy for the issue:
function getFive(){
var data;
setTimeout(function(){ // Set a timer for one second in the future
data = 5; // After a second, do this
}, 1000);
return data;
}
document.body.innerHTML = getFive(); // `undefined` here and not 5
Answer
Solution:
You are using Ajax incorrectly. The idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
That is:
function handleData( responseData ) {
// Do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
Returning anything in the submit handler will not do anything. You must instead either hand off the data, or do what you want with it directly inside the success function.
Answer
Solution:
I will answer with a horrible-looking, hand-drawn comic. The second image is the reason why result
is undefined
in your code example.
Answer
Solution:
The simplest solution is to create a JavaScript function and call it for the Ajax success
callback.
function callServerAsync(){
$.ajax({
url: '...',
success: function(response) {
successCallback(response);
}
});
}
function successCallback(responseObj){
// Do something like read the response and show data
alert(JSON.stringify(responseObj)); // Only applicable to a JSON response
}
function foo(callback) {
$.ajax({
url: '...',
success: function(response) {
return callback(null, response);
}
});
}
var result = foo(function(err, result){
if (!err)
console.log(result);
});
Answer
Solution:
Angular 1
People who are using AngularJS, can handle this situation using promises.
Here it says,
Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together.
You can find a nice explanation here also.
An example found in documentation mentioned below.
promiseB = promiseA.then(
function onSuccess(result) {
return result + 1;
}
,function onError(err) {
// Handle error
}
);
// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1.
Angular 2 and later
In Angular 2 with look at the following example, but its recommended to use observables with Angular 2.
search(term: string) {
return this.http
.get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
.map((response) => response.json())
.toPromise();
}
You can consume that in this way,
search() {
this.searchService.search(this.searchField.value)
.then((result) => {
this.result = result.artists.items;
})
.catch((error) => console.error(error));
}
See the original post here. But TypeScript does not support native ES6 Promises, if you want to use it, you might need plugin for that.
Additionally, here is the promises specification.
Answer
Solution:
Most of the answers here give useful suggestions for when you have a single async operation, but sometimes, this comes up when you need to do an asynchronous operation for each entry in an array or other list-like structure. The temptation is to do this:
// WRONG
var results = [];
theArray.forEach(function(entry) {
doSomethingAsync(entry, function(result) {
results.push(result);
});
});
console.log(results); // E.g., using them, returning them, etc.
Example:
// WRONG
var theArray = [1, 2, 3];
var results = [];
theArray.forEach(function(entry) {
doSomethingAsync(entry, function(result) {
results.push(result);
});
});
console.log("Results:", results); // E.g., using them, returning them, etc.
function doSomethingAsync(value, callback) {
console.log("Starting async operation for " + value);
setTimeout(function() {
console.log("Completing async operation for " + value);
callback(value * 2);
}, Math.floor(Math.random() * 200));
}
.as-console-wrapper { max-height: 100% !important; }
Answer
Solution:
Have a look at this example:
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$http) {
var getJoke = function(){
return $http.get('http://api.icndb.com/jokes/random').then(function(res){
return res.data.value;
});
}
getJoke().then(function(res) {
console.log(res.joke);
});
});
As you can see getJoke
is returning a resolved promise (it is resolved when returning res.data.value
). So you wait until the $http.get request is completed and then console.log(res.joke) is executed (as a normal asynchronous flow).
This is the plnkr:
http://embed.plnkr.co/XlNR7HpCaIhJxskMJfSg/
ES6 way (async - await)
(function(){
async function getJoke(){
let response = await fetch('http://api.icndb.com/jokes/random');
let data = await response.json();
return data.value;
}
getJoke().then((joke) => {
console.log(joke);
});
})();
Answer
Solution:
This is one of the places which two-way data binding or store concept that's used in many new JavaScript frameworks will work great for you...
So if you are using Angular, React, or any other frameworks which do two-way data binding or store concept, this issue is simply fixed for you, so in easy words, your result is undefined
at the first stage, so you have got result = undefined
before you receive the data, then as soon as you get the result, it will be updated and get assigned to the new value which response of your Ajax call...
But how you can do it in pure JavaScript or jQuery for example as you asked in this question?
You can use a callback, promise and recently observable to handle it for you. For example, in promises we have some function like success()
or then()
which will be executed when your data is ready for you. The same with callback or the subscribe function on an observable.
For example, in your case which you are using jQuery, you can do something like this:
$(document).ready(function(){
function foo() {
$.ajax({url: "api/data", success: function(data){
fooDone(data); // After we have data, we pass it to fooDone
}});
};
function fooDone(data) {
console.log(data); // fooDone has the data and console.log it
};
foo(); // The call happens here
});
For more information, study promises and observables which are newer ways to do this async stuff.
Answer
Solution:
It's a very common issue we face while struggling with the 'mysteries' of JavaScript. Let me try demystifying this mystery today.
Let's start with a simple JavaScript function:
function foo(){
// Do something
return 'wohoo';
}
let bar = foo(); // 'bar' is 'wohoo' here
That's a simple synchronous function call (where each line of code is 'finished with its job' before the next one in sequence), and the result is same as expected.
Now let's add a bit of twist, by introducing a little delay in our function, so that all lines of code are not 'finished' in sequence. Thus, it will emulate the asynchronous behavior of the function:
function foo(){
setTimeout( ()=> {
return 'wohoo';
}, 1000)
}
let bar = foo() // 'bar' is undefined here
So there you go; that delay just broke the functionality we expected! But what exactly happened? Well, it's actually pretty logical if you look at the code.
The function foo()
, upon execution, returns nothing (thus returned value is undefined
), but it does start a timer, which executes a function after 1 second to return 'wohoo'. But as you can see, the value that's assigned to bar is the immediately returned stuff from foo(), which is nothing, i.e., just undefined
.
So, how do we tackle this issue?
Let's ask our function for a promise. Promise is really about what it means: it means that the function guarantees you to provide with any output it gets in future. So let's see it in action for our little problem above:
function foo(){
return new Promise((resolve, reject) => { // I want foo() to PROMISE me something
setTimeout ( function(){
// Promise is RESOLVED, when the execution reaches this line of code
resolve('wohoo') // After 1 second, RESOLVE the promise with value 'wohoo'
}, 1000 )
})
}
let bar;
foo().then( res => {
bar = res;
console.log(bar) // Will print 'wohoo'
});
Thus, the summary is - to tackle the asynchronous functions like Ajax-based calls, etc., you can use a promise to resolve
the value (which you intend to return). Thus, in short you resolve value instead of returning, in asynchronous functions.
UPDATE (Promises with async/await)
Apart from using then/catch
to work with promises, there exists one more approach. The idea is to recognize an asynchronous function and then wait for the promises to resolve, before moving to the next line of code. It's still just the promises
under the hood, but with a different syntactical approach. To make things clearer, you can find a comparison below:
then/catch version:
function saveUsers(){
getUsers()
.then(users => {
saveSomewhere(users);
})
.catch(err => {
console.error(err);
})
}
async/await version:
async function saveUsers(){
try{
let users = await getUsers()
saveSomewhere(users);
}
catch(err){
console.error(err);
}
}
Answer
Solution:
Another approach to return a value from an asynchronous function, is to pass in an object that will store the result from the asynchronous function.
Here is an example of the same:
var async = require("async");
// This wires up result back to the caller
var result = {};
var asyncTasks = [];
asyncTasks.push(function(_callback){
// some asynchronous operation
$.ajax({
url: '...',
success: function(response) {
result.response = response;
_callback();
}
});
});
async.parallel(asyncTasks, function(){
// result is available after performing asynchronous operation
console.log(result)
console.log('Done');
});
I am using the result
object to store the value during the asynchronous operation. This allows the result be available even after the asynchronous job.
I use this approach a lot. I would be interested to know how well this approach works where wiring the result back through consecutive modules is involved.
Answer
Solution:
While promises and callbacks work fine in many situations, it is a pain in the rear to express something like:
if (!name) {
name = async1();
}
async2(name);
You'd end up going through async1
; check if name
is undefined or not and call the callback accordingly.
async1(name, callback) {
if (name)
callback(name)
else {
doSomething(callback)
}
}
async1(name, async2)
While it is okay in small examples it gets annoying when you have a lot of similar cases and error handling involved.
Fibers
helps in solving the issue.
var Fiber = require('fibers')
function async1(container) {
var current = Fiber.current
var result
doSomething(function(name) {
result = name
fiber.run()
})
Fiber.yield()
return result
}
Fiber(function() {
var name
if (!name) {
name = async1()
}
async2(name)
// Make any number of async calls from here
}
You can checkout the project here.
Answer
Solution:
The following example I have written shows how to
- Handle asynchronous HTTP calls;
- Wait for response from each API call;
- Use Promise pattern;
- Use Promise.all pattern to join multiple HTTP calls;
This working example is self-contained. It will define a simple request object that uses the window XMLHttpRequest
object to make calls. It will define a simple function to wait for a bunch of promises to be completed.
Context. The example is querying the Spotify Web API endpoint in order to search for playlist
objects for a given set of query strings:
[
"search?type=playlist&q=%22doom%20metal%22",
"search?type=playlist&q=Adele"
]
For each item, a new Promise will fire a block - ExecutionBlock
, parse the result, schedule a new set of promises based on the result array, that is a list of Spotify user
objects and execute the new HTTP call within the ExecutionProfileBlock
asynchronously.
You can then see a nested Promise structure, that lets you spawn multiple and completely asynchronous nested HTTP calls, and join the results from each subset of calls through Promise.all
.
NOTE
Recent Spotify search
APIs will require an access token to be specified in the request headers:
-H "Authorization: Bearer {your access token}"
So, you to run the following example you need to put your access token in the request headers:
var spotifyAccessToken = "YourSpotifyAccessToken";
var console = {
log: function(s) {
document.getElementById("console").innerHTML += s + "<br/>"
}
}
// Simple XMLHttpRequest
// based on https://davidwalsh.name/xmlhttprequest
SimpleRequest = {
call: function(what, response) {
var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Internet Explorer
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {}
}
}
// State changes
request.onreadystatechange = function() {
if (request.readyState === 4) { // Done
if (request.status === 200) { // Complete
response(request.responseText)
}
else
response();
}
}
request.open('GET', what, true);
request.setRequestHeader("Authorization", "Bearer " + spotifyAccessToken);
request.send(null);
}
}
//PromiseAll
var promiseAll = function(items, block, done, fail) {
var self = this;
var promises = [],
index = 0;
items.forEach(function(item) {
promises.push(function(item, i) {
return new Promise(function(resolve, reject) {
if (block) {
block.apply(this, [item, index, resolve, reject]);
}
});
}(item, ++index))
});
Promise.all(promises).then(function AcceptHandler(results) {
if (done) done(results);
}, function ErrorHandler(error) {
if (fail) fail(error);
});
}; //promiseAll
// LP: deferred execution block
var ExecutionBlock = function(item, index, resolve, reject) {
var url = "https://api.spotify.com/v1/"
url += item;
console.log( url )
SimpleRequest.call(url, function(result) {
if (result) {
var profileUrls = JSON.parse(result).playlists.items.map(function(item, index) {
return item.owner.href;
})
resolve(profileUrls);
}
else {
reject(new Error("call error"));
}
})
}
arr = [
"search?type=playlist&q=%22doom%20metal%22",
"search?type=playlist&q=Adele"
]
promiseAll(arr, function(item, index, resolve, reject) {
console.log("Making request [" + index + "]")
ExecutionBlock(item, index, resolve, reject);
}, function(results) { // Aggregated results
console.log("All profiles received " + results.length);
//console.log(JSON.stringify(results[0], null, 2));
///// promiseall again
var ExecutionProfileBlock = function(item, index, resolve, reject) {
SimpleRequest.call(item, function(result) {
if (result) {
var obj = JSON.parse(result);
resolve({
name: obj.display_name,
followers: obj.followers.total,
url: obj.href
});
} //result
})
} //ExecutionProfileBlock
promiseAll(results[0], function(item, index, resolve, reject) {
//console.log("Making request [" + index + "] " + item)
ExecutionProfileBlock(item, index, resolve, reject);
}, function(results) { // aggregated results
console.log("All response received " + results.length);
console.log(JSON.stringify(results, null, 2));
}
, function(error) { // Error
console.log(error);
})
/////
},
function(error) { // Error
console.log(error);
});
<div id="console" />
Answer
Solution:
The short answer is, you have to implement a callback like this:
function callback(response) {
// Here you can do what ever you want with the response object.
console.log(response);
}
$.ajax({
url: "...",
success: callback
});
Answer
Solution:
JavaScript is single threaded.
The browser can be divided into three parts:
Event Loop
Web API
Event Queue
The event loop runs for forever, i.e., kind of an infinite loop. The event queue is where all your functions are pushed on some event (example: click).
This is one by one carried out of queue and put into the event loop which executes this function and prepares itself for the next one after the first one is executed. This means execution of one function doesn't start until the function before it in the queue is executed in the event loop.
Now let us think we pushed two functions in a queue. One is for getting a data from the server and another utilises that data. We pushed the serverRequest() function in the queue first and then the utiliseData() function. The serverRequest function goes in the event loop and makes a call to server as we never know how much time it will take to get data from server, so this process is expected to take time and so we busy our event loop thus hanging our page.
That's where Web API come into the role. It takes this function from the event loop and deals with the server making the event loop free, so that we can execute the next function from the queue.
The next function in the queue is utiliseData() which goes in the loop, but because of no data available, it goes to waste and execution of the next function continues until the end of the queue. (This is called Async calling, i.e., we can do something else until we get data.)
Let us suppose our serverRequest() function had a return statement in code. When we get back data from the server Web API, it will push it in the queue at the end of queue.
As it gets pushed at the end of the queue, we cannot utilise its data as there isn't any function left in o
Source