javascript 在angularjs $q 中将参数传递给promise 的成功回调
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32465183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing parameters to promise's success callback in angularjs $q
提问by Richard.Davenport
I realize this is a very similar question to this one. But I'm still unclear on how to do it in my situation. Just need some help with a successful callback.
我知道这是这是一个非常类似的问题一个。但我仍然不清楚如何在我的情况下做到这一点。只需要一些成功回调的帮助。
This is what works:
这是有效的:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(log);
}
function log(response) {
logger.debug(response);
return response;
}
This is what I want to accomplish:
这就是我想要完成的:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(log(response, logMessage);
}
function log(response, logMessage) {
logger.debug(logMessage, response);
return response;
}
回答by Rohit Jain
You can use this:
你可以使用这个:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
return $http.post(GetStuff, { custId: accountNumber })
.then(
function success(response) {
return log(response, logMessage);
}
);
}
回答by Shan Robertson
Depending on your preference/requirements you could do a few things. I normally write promise callbacks like this, so you could do:
根据您的偏好/要求,您可以做一些事情。我通常写这样的承诺回调,所以你可以这样做:
.then(function success(response){
return log(response, logMessage);
});
or, depending on how you feel about this way (i know some people don't like it, i try to avoid unless absoluley nessesary)
或者,取决于你对这种方式的感受(我知道有些人不喜欢它,除非绝对必要,否则我会尽量避免)
.then(log.bind(null, response, logMessage));
Do either of these work for you?
这些对你有用吗?
回答by Ali Adravi
See if it can help you:
看看它是否可以帮助您:
function getStuff(accountNumber) {
var logMessage = 'POST GetStuff';
var deferred = $q.defer();
return $http.post(GetStuff, { custId: accountNumber })
.success(function(response){
deferred.resolve(response);
log(response, logMessage);
}).error(function(){
deferred.reject();
})
return deferred.promise;
}