0

I have an ajax call that gets data from a file. i use this data to parse some elements on the window.
However, I also use another ajax call before, and i use it to decide which parameteres to send in the other ajax call..

I know how to "chain" the calls, using the success event. but, in some cases it is impossible to chain them and they are called separately. in that case i need another mechanism to do the trick.

for now i use timers and flags.. but i understood that Promises are the best modern way. but i can't figure out how to use it in that context.

can anyone help with a skeleton, explained - code?

thank you

yossi
  • 3,090
  • 7
  • 45
  • 65
  • Take a look at the fetch API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch it is promise based and you can create a nice chain :) fetch('someUrl').then(res => res.json()).then(res => { return fetch('anotherUrl').then(res => res.json()).then(res => ... – noa-dev Jan 21 '19 at 10:15
  • Instead of putting stuff in `success` callbacks, put it in [`then` callbacks from which you can `return`](https://stackoverflow.com/a/22562045/1048572). Then [chain them](https://stackoverflow.com/a/22000931/1048572). [That's all](https://stackoverflow.com/a/25756564/1048572)! – Bergi Jan 21 '19 at 10:24
  • Please show us the code you have, and especially the situation where you think the normal approach doesn't work any more. Otherwise this question is hardly answerable. – Bergi Jan 21 '19 at 10:25

1 Answers1

0

$.ajax returns a jQuery Deferred object, which can be used like a Promise. You can assign the result to a variable, then use that later to do the next call.

var promise = $.ajax(...);
...
promise.then(function(result) {
    var second_promise = $.ajax(...);
    ...
    second_promise.then(...);
});
Barmar
  • 741,623
  • 53
  • 500
  • 612