在阅读了一页又一页有关 Promise 的内容之后,我仍然无法找出在类函数内返回 Promise(ES6 规范)的正确方法。
以下是我尝试过的各种选项。
utils.getMyPhotos()
返回一个 promise 。
1) Return the promise AND it's values
profilePictures(){
return utils.getMyPhotos().then(function(result){
var photosArray = result;
photosArray.forEach(function(element) {
this._list.push(new Picture(
element.src,
element.caption
));
}, this);
return this._list;
},function(error){
console.log(error);
return error;
});
}
2) Only return the promise' values
profilePictures(){
utils.getMyPhotos().then(function(result){
var photosArray = result;
photosArray.forEach(function(element) {
this._list.push(new Picture(
element.src,
element.caption
));
}, this);
return this._list;
},function(error){
console.log(error);
return error;
});
}
3)Create a new Promise and return it
profilePictures(){
return new Promise(function(fulfill,reject){
utils.getMyPhotos().then(function(result){
var photosArray = result;
photosArray.forEach(function(element) {
this._list.push(new Picture(
element.src,
element.caption
));
}, this);
fulfill(this._list);
},function(error){
console.log(error);
reject(error);
});
}
}
我尝试按如下方式使用上述函数:
pictures.profilePictures().then(function(result){
console.log("all good");
console.dump(result);
},function(error){
console.log("errors encountered");
console.log(error);
});
然而,在 CLI 中,我只看到“遇到错误”,后跟一个空的 error
对象。
我做错了什么?
最佳答案
- 您在这里做的是正确的事情,但是您的错误处理程序不会捕获来自其同级成功处理程序的错误。我还建议您不要改变实例变量
this._list
并返回这样做的结果,因为从函数名称中不清楚 this 是它会做什么。或者也许我很挑剔。无论如何,请参阅下面的推荐重构。 - 您不会退回任何东西。 (请参阅 @Bergi's answer 了解为什么返回很重要!)
- 是 Promise 反模式。 Watch out for those .
______
重构(1)
我已经移动了错误处理程序,以便它能够捕获所有先前处理程序中的错误。我们在记录错误后抛出错误,这样我们就可以捕获 API 使用过程中的错误,而不是在内部处理它们。尽管这可能不是您想要做的,但这意味着错误不会被神秘地吞没。
profilePictures () {
return utils.getMyPhotos()
.then(function (result) {
return result.map(function (element) {
return new Picture(element.src, element.caption);
});
})
.then(null, function (error){
console.log(error);
throw err;
});
}
消费它:
instance.profilePictures()
.then(function (pics) {
pics.forEach(function (pic) {
// Do something with the Picture instance
});
})
.then(null, function (err) {
// Handle the error
});
关于Javascript ES6 promise 在类函数内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38267220/