Search code examples
javascriptreactjssuperagent

Superagent & Fetch returning promises -- How to handlle these?


Forgive me for this question which is likely to be an easy solve for a more experienced JS programmer. I've been reading up on superagent and fetch, trying to get REST calls working. (I was able to get odata working correctly but I now need REST). However, I'm getting confused on promises. I'm currently trying to make a simple request.get (or fetch.get) with the following code:

this.ticketList = Request.get(url).then((response) => {
    return response.body.Tickets;
});
console.log(this.ticketList); // Returns a promise..?

I'm not familiar with promises and don't know how to handle this. All the documentation I've read says async calls are a good thing, but my application is linear and requires data from the previous call before continuing. I don't need a promise, I need the full response. (Please correct me if my limited understanding of promises/ajax is wrong!)

How can I change the above code to give me the response object I want? (JSON preferred) Or, how do I handle a promise to get the data I need?

Thanks, Charlie


Solution

  • Basically, with promises, you deal with this by chaining thens together.

    Request.get(url)
           .then((response) => {
               return response.body.Tickets;
            })
           .then((ticketList) => {
               console.log(ticketList);
            });
    

    In this specific case there's really not a benefit to breaking this up into two thens instead of just working with response.body.Tickets directly. Typically you'd do everything here until the next point you needed to make an async call, and then you'd get a new promise. For example:

    Request.get(url)
           .then((response) => {
               var ticketList = response.body.Tickets;
               console.log(ticketList);
               return Request.get(url2);
            })
           .then((response2) => {
               /* ... */
            });
    

    Essentially, if you have a linear set of operations, as soon as you make your first async call, everything following that call happens inside a callback provided in a then statement (or a catch statement to handle a rejected promise).