javascript-Angular Promises:最佳做法和不同技术的优点/缺点
作者:互联网
这个问题已经在这里有了答案: > What is the explicit promise construction antipattern and how do I avoid it? 2个
我正在学习Angular,遇到了两种方法来进行返回诺言的呼叫.我想知道一种方法是否比另一种更好,和/或何时使用每种方法.
第一种技术:
function getSomeDataFromServer() {
var deferred = $q.defer();
if (myData) {
// call to backend was previously made and myData is already loaded
deferred.resolve(myData);
} else {
// get data from server
$http.get(my_url_endpoint).then(function(response) {
// cacheResult() will set myData = response.data
deferred.resolve(cacheResult(response));
});
}
return deferred.promise;
}
第二种技术:
function getSomeDataFromServer() {
if (myData) {
// call to backend was previously made and myData is already loaded
return $q.when(myData);
} else {
// get data from server
return $http.get(my_url_endpoint).then(function(response) {
// cacheResult() will set myData = response.data
return cacheResult(response);
});
}
}
解决方法:
总是喜欢第二种选择.第一种选择是一种反模式,通常在开发人员不完全了解承诺的性质时出现.延迟对象(var deferred = $q.defer();)使用when you have some asynchronous code that uses callbacks but needs to work with your promise based code.
您在Angular中所做的大多数异步操作都会返回Promise,因此,在处理依赖于回调的第3方库时,通常只使用deferreds.
在此示例中,$http本身返回一个promise,因此不必创建新的延迟对象.返回$http承诺本身就足够了.
标签:angularjs,promise,javascript,angular-promise 来源: https://codeday.me/bug/20191028/1951701.html