javascript tutorial - [Solved-5 Solutions] n asynchronous call - javascript - java script - javascript array



Problem:

How do we return the response from n asynchronous call ?

Solution 1:

  • We 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 we want with the data
    console.log(responseData);
}

$.ajax({
    url: "hi.php",
    ...
    success: function ( data, status, XHR ) {
        handleData(data);
    }
});
click below button to copy the code. By JavaScript tutorial team
  • Returning anything in the submit handler will not do anything. We must instead either hand off the data, or do what we want with it directly inside the success function.

Solution 2:

Angular1

For 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.
  • We can find a nice explanation here also.
  • Example found in docs 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.
click below button to copy the code. By JavaScript tutorial team

Angular2 and Later

In Angular2 with look at the following example, but its recommended to use Observables with Angular2.

search(term: string) {
     return this.http
  .get(`https://api.spotify.com/v1/search?q=${term}&type=artist`)
  .map((response) => response.json())
  .toPromise();
}
click below button to copy the code. By JavaScript tutorial team

We 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));
}
click below button to copy the code. By JavaScript tutorial team
  • See the original post here. But Typescript does not support native es6 Promises, if we want to use it, we might need plugin for that.
  • Additionally here is the promises spec define here.

Solution 3:

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);
    });
});
click below button to copy the code. By JavaScript tutorial team

As we can see getJoke is returning a resolved promise (it is resolved when returning res.data.value). So we wait until the $http.get request is completed and then console.log(res.joke) is executed (as a normal asynchronous flow).

Solution 4:

here's a version returning a Promiseinstead:

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);
    });
});
click below button to copy the code. By JavaScript tutorial team

Solution 5:

If doSomethingAsync gives we a Promise, if we can use ES2017+ syntax (perhaps with a transpiler like Babel), we can use an async function with for-of and await:

async function doSomethingWith(theArray) {
    const results = [];
    for (const entry of theArray) {
        results.push(await doSomethingAsync(entry));
    }
    return results;
}
doSomethingWith(theArray).then(results => {
    console.log("Results:", results);
});
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - n asynchronous call