问题
Since Promise
is now officially spec-ed and all, how do I convert the $q.defer()
promise creation in the following snippet to use the $q(function (resolve, reject) {})
constructor syntax instead?
// Cancel any ongoing $http request so that only the most recent $http
// callback gets invoked
var canceller;
function getThing(id) {
if (canceller) canceller.resolve();
canceller = $q.defer();
return $http.get('/api/things/' + id, {
timeout: canceller.promise
});
}
(Fyi from $http docs: timeout
is "… in milliseconds, or promise that should abort the request when resolved.")
回答1:
I'd do it like this:
var canceller = null;
function getThing(id) {
if (canceller) canceller();
return Promise.resolve($http.get('/api/things/' + id, {
timeout: new Promise(function(resolve) {
canceller = resolve;
})
}));
}
I'll assume you'd never have used canceller.reject
anyway, so you can just keep around the resolve
function itself to call it next time.
来源:https://stackoverflow.com/questions/36165800/how-to-use-qs-constructor-syntax-with-angular-https-config-timeout