[英]Javascript ES6 promise inside class function
在阅读了有关promise的页面和页面之后,我仍然无法找出在类函数内返回promise(ES6规范)的正确方法。
这是我尝试过的各种选项。 utils.getMyPhotos()
返回一个承诺。
1)兑现诺言及其价值
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)只返回诺言的值
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)创建一个新的Promise并返回
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
突变, 并返回执行此操作的结果,因为从函数名称中尚不清楚这是它将执行的操作。 也许我在挑剔。 无论如何,请参阅下面的建议重构。 ______
重构(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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.