How do I return the response/result from a function foo that makes an asynchronous request?
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 Node.js:
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` }
- Adam asked 6 months ago
- You must login to post comments
In Angular 1
People who are using AngularJS, can handle this situation using promises.
Promises can be used to unnest asynchronous functions and allows one to chain multiple functions together.
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.
In Angular 2
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)); }
- Adam answered 6 months ago
- You must login to post comments
Please login first to submit.