mrQ*_*RTY 3 javascript node.js promise
我们如何处理thenPromise 函数中发生的错误?
getLocationId(lat, lon, callback)
{
let self = this;
return this._geocoder.reverse({lat: lat, lon: lon})
.then(this._parse)
.catch(function(err) {
callback(err);
});
}
_parse(res)
{
if (res.length < 1)
throw new Error('No results from Maps API');
let value = res[0].administrativeLevels;
if (!value || value.length < 1) {
throw new Error('No administrative levels available');
}
if ('level2long' in value)
return value.level2long;
if ('level1long' in value)
return value.level1long;
throw new Error('No suitable location found');
}
Run Code Online (Sandbox Code Playgroud)
例如,我如何处理this._parse抛出错误?我认为catchPromise 的函数只处理reject处理程序。它是否也处理 中抛出的错误then?
任何处理程序中抛出的异常.then()都会被 Promise 基础设施自动捕获,并将当前的 Promise 链变成被拒绝的 Promise。然后,链将跳转到下一个.catch()处理程序,其中异常将成为错误拒绝原因。
这是一个例子:
Promise.resolve().then(function() {
throw "foo";
}).then(function() {
console.log("in 2nd .then() handler"); // will not get here
}).catch(function(err) {
console.log(err); // will show "foo"
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5609 次 |
| 最近记录: |