承诺是对语句的抽象,允许我们用异步代码同步表达自己。它们代表一项一次性任务的执行。
它们还提供异常处理,就像普通代码一样,您可以从Promise返回或抛出。
您想要的同步代码是:
try{ try{ var res = $http.getSync("url"); res = someProcessingOf(res); } catch (e) { console.log("Got an error!",e); throw e; // rethrow to not marked as handled } // do more stuff with res} catch (e){ // handle errors in processing or in error.}
承诺的版本非常相似:
$http.get("url").then(someProcessingOf).catch(function(e){ console.log("got an error in initial processing",e); throw e; // rethrow to not marked as handled, // in $q it's better to `return $q.reject(e)` here}).then(function(res){ // do more stuff}).catch(function(e){ // handle errors in processing or in error.});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)