Greg Gum Greg Gum - 4 months ago 7
Javascript Question

How to return promise

I have not been able to get my wits around promises.

I have this function:

response(theResponse) {
return theResponse.json();
}


theReponse.json()
is code which returns a promise.

This works, and returns a promise which resolves to an array.

However, I need to modify this so I can get access to the array, and then process the array, and then return it in a promise.

How do I do that?

Answer

if that json() method returns promise then you can use then()

response(theResponse) {
    return theResponse.json().then(function(arr) {
      //do something with arr 
      return arr;
    }); // then() returns new promise so it can be chained
}

Check "promise chaining" here.

Comments