Greg Gum Greg Gum - 1 year ago 92
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();

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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download