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:
- 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.
Angular2 and Later
In Angular2 with look at the following example, but its recommended to use Observables with Angular2.
We can consume that in this way,
- 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:
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 Promise
instead:
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: