我很难理解处理错误的最佳方法。 下面的代码是一个很好的做法吗?这是承诺中错误处理的正确用法吗?
有更好,更短,更容易阅读的方式来处理流量和错误?
如何编写代码来处理所有错误,以免被吞下?谢谢。
privateProperties.setSearchedData = function (data, searchFor) {
return new Promise(function (resolve, reject) {
switch (searchFor) {
case "photos":
try {
var photoItems = [];
if (data.items && data.items.constructor === Array) {
data.items.forEach(function (value) {
if (value.link) {
photoItems.push(value.link);
} else {
console.error('Link is undefined');
reject(new Error('Link is undefined'));
}
});
privateProperties._uiInstances['main'].uiReference.set("photos.photoItems",photoItems)
.then(resolve(photoItems))
.catch(function (error) {
reject(error);
})
} else {
reject(new Error('Data.items is undefined or not array'));
}
} catch (e) {
throw e;
}
break;
case "videos":
break
}
});
};
这里的哪个调用是异步的?它是否是'uiReference.set'?你在回复什么? –
是uiReference.set是异步的 – Mihai
否。避免['Promise' constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-要避免的,它)!事实上,你在这里似乎并不需要承诺。 – Bergi