How do we return the response from n asynchronous call ?
- 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.
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.
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).
here's a version returning a
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: