Let’s define a function to simulate calling API via Promise
and setTimeout()
:
1 | var callAPI = (api, arg) => new Promise((resolve, reject)=>{ // <- callAPI() always return this promise |
Use like this:
1 | callAPI("AddUser", { username: "ib", password: "ib" }).then((x)=>{ |
Result
1 | API "AddUser" called successfully! ==> {"username":"ib","password":"ib"} |
Call Multiple APIs Simultaneously
When you have to call a lot of asynchronous APIs simultaneously, you may use Promise.all()
like this::
1 | var newUsers = [ |
Result
1 | API "AddUser" called successfully! ==> {"username":"marry","password":"marry"} |
Call Multiple APIs One-By-One
Now consider: how to call APIs one-by-one? That is to say, after previous API has replied, then call another?
The answer is: pass another Promise
into resolve()
:
1 | var newUsers = [ |
Result
1 | API "AddUser" called successfully! ==> {"username":"ib","password":"ib"} |
When you pass a
Promise
object intoresolve()
, that passedPromise
will going to be resolved.
See Promise.resolve() and Promise to get more details.