2016-08-04 48 views
0

我还没有能够让我的智慧围绕承诺。如何退还承诺

我有这样的功能:

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

theReponse.json()是代码,它返回一个承诺。

这个工作,并返回一个承诺,解析为一个数组。

但是,我需要修改这个,所以我可以访问数组,然后处理该数组,然后将其返回到承诺中。

我该怎么做?

+1

您的参数与函数名称相同。那对我来说不好看。 –

+1

我在你的问题中没有看到任何承诺。谨慎解释? – 4castle

+1

'return theResponse.json()。then(arr => ...);' – zerkms

回答

1

组成承诺管线如果json()方法返回的承诺,那么你可以使用then()

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

检查 “的承诺链接” here

+0

谢谢,那是有效的。 –

1

可以使用Promise#then()

function response(theResponse) { 
    return theResponse.json().then(function(array) { 
    // process array 
    return array; 
    }); 
} 
1

只要添加到其他答案,你应该总是抓住你的承诺,使错误不会被“吞噬”。

response(theResponse) { 
    return theResponse 
      .json() 
      .then(arr => arr) // handle resolve 
      .catch(err => err); // handle reject 
}