0

I know that we can use promise based http client like axios to use the then api like this

axios(url).then(success, error)

But If I want to send 2 simultaneous ajax requests, I will still have to restore to using jquery's $.when

$.when(promise1, promise2).then(success, error)

What is the alternative to $.when if I don't want to use a heavy library like jquery and use some lightweight lib.

1
  • 1
    Or code something on your own, it is not that hard to do. Feb 11 '17 at 3:03
2

You can use Promise.all()

Promise.all([promise1, promise2]).then(success, error);
3
1

Use $Q library: https://github.com/kriskowal/q for your purpose you can use $Q.all

2
  • im not using angular
    – Probosckie
    Feb 11 '17 at 3:21
  • Its not angular dependent. Rather angular got its implementation using this library as core. You can run this in your desired browser and see if it will work.
    – Rikin
    Feb 11 '17 at 14:04
0

As our friend Rikin said above, using Q library is definitely a good choice. jQuery.when() doesn't continue the requests if any of those requests parameters fails.

Q have methods that makes this possible. Look, imagine that you have fn1 and fn3 that gives you HTTP 200 and fn2 returns HTTP 404, with this method Q.allSettled it will work perfectly.

Q.allSettled([fn1(), fn2(), fn3()])
.then(function(f1Result, f2Result, f3Result) {
   // your code that will run every time...
});

If you need to use it in your web project, follow these steps (you will need to have npm installed in your machine):

1) Go to https://github.com/kriskowal/q and clone/download the repo.

2) Then to the folder where you cloned the repo and run npm install.

3) Finally, npm run minify. It will generate the q.min.js and you can use in your projects.

For more info, go to Q wiki reference: https://github.com/kriskowal/q/wiki/API-Reference

Cheeers~

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.