我无法在承诺中获得智慧。
我有这个功能:
response(theResponse) {
return theResponse.json();
}
theReponse.json()
是返回承诺的代码。
这样可行,并返回一个解析为数组的promise。
但是,我需要修改它,以便我可以访问数组,然后处理数组,然后在promise中返回它。
我该怎么做?
答案 0 :(得分:1)
您可以使用Promise#then()
function response(theResponse) {
return theResponse.json().then(function(array) {
// process array
return array;
});
}
答案 1 :(得分:1)
如果json()
方法返回promise,则可以使用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。
答案 2 :(得分:1)
只是为了添加其他答案,你应该始终抓住你的承诺,以免错误被“吞噬”。
response(theResponse) {
return theResponse
.json()
.then(arr => arr) // handle resolve
.catch(err => err); // handle reject
}