使用 jQuery deferreds,我习惯于像这样检查当前状态:
var defer = $.Deferred();
defer.state(); //Returns the state of the deferred, eg 'resolved'
有没有办法对 Angular deferreds 做同样的事情?(甚至更好的承诺)
使用 jQuery deferreds,我习惯于像这样检查当前状态:
var defer = $.Deferred();
defer.state(); //Returns the state of the deferred, eg 'resolved'
有没有办法对 Angular deferreds 做同样的事情?(甚至更好的承诺)
更新:
由于 $q 的重构,这现在是可能的,尽管没有记录:
promise.$$state.status === 0 // pending
promise.$$state.status === 1 // resolved
promise.$$state.status === 2 // rejected
原文:
与大多数 Promise 库(Bluebird、Q、when、RSVP 等)不同,$q 不公开同步检查 API。
没有办法从外部实现这一点。
您必须调用.then
承诺,并且该处理程序中的代码将在承诺履行时运行。
你的问题的答案是:是的,有办法。其他答案很好地涵盖了$q
. $q
但是,使用服务的$provide
装饰器函数很容易添加 state 属性。
$provide.decorator('$q', function ($delegate) {
var defer = $delegate.defer;
$delegate.defer = function() {
var deferred = defer();
deferred.promise.state = deferred.state = 'pending';
deferred.promise.then(function() {
deferred.promise.state = deferred.state = 'fulfilled';
}, function () {
deferred.promise.state = deferred.state = 'rejected';
});
return deferred;
};
return $delegate;
});
将此装饰器放在一个config
块中,所有实例化的deferred和promise对象都将具有一个值为pending、$q
fulfilled或denied的属性。state
您正在有效地修改 $q 本身,用另一个 deferred 包装每个 deferred
实际上并非如此。$q
的原始defer()
构造函数只被调用一次。它只是通过在内部附加一个事件处理程序来装饰附加功能then
。[请注意,附加回调defer
的结果是附加的对象被实例化,该附加then
回调是随每个延迟对象自动创建的......这是可以预期的,因为这是 Angular 在内部的工作方式。]
这是行不通的,因为不应使用 deferred 创建 Promise,而是将其与从 apis 返回的 Promise 链接起来
请注意,此代码将装饰由服务创建的每个延迟(以及对象)。这意味着任何使用 $q 的 API 都将自动使用property进行修饰。因此,无论您如何使用,无论是使用某些 API 还是单独使用,此解决方案都装饰了object 和,并且我提供了 plunk来证明这一点。promise
$q
state
$q
deferred
promise
这种方法是可单元测试的,它保证不会破坏任何已经在使用的应用程序$q
,并且它是灵活的,你以后可以添加额外的装饰器$q
而不修改旧的。
不幸的是,这看起来不太可能$q
。您必须将此代码放入您的then
方法中。
myPromise()
.then(function() {
// everything in here resolved
},
function() {
// everything in here rejected
},
function() {
// everything in here pending (with progress back)
});
这适用于 Q 库,不是 Angular 的$q
,而是类似的。
Angular 受到Q
库的启发,查看源代码,它实际上并没有那么可怕。https://github.com/kriskowal/q/blob/v1/q.js
你可以使用myPromise.inspect().state
有['pending', 'rejected', 'fulfilled']
你还有:
myPromise.isFulfilled();
myPromise.isPending();
myPromise.isRejected();
查看此 JSfiddle 并打开控制台以获取记录的结果。 http://jsfiddle.net/S6LzP/
更细化,查看defer
第 488 行的函数:
function defer() {
// if "messages" is an "Array", that indicates that the promise has not yet
// been resolved. If it is "undefined", it has been resolved. Each
// element of the messages array is itself an array of complete arguments to
// forward to the resolved promise. We coerce the resolution value to a
// promise using the `resolve` function because it handles both fully
// non-thenable values and other thenables gracefully.
var messages = [], progressListeners = [], resolvedPromise;
var deferred = object_create(defer.prototype);
var promise = object_create(Promise.prototype);
promise.promiseDispatch = function (resolve, op, operands) {
var args = array_slice(arguments);
if (messages) {
messages.push(args);
if (op === "when" && operands[1]) { // progress operand
progressListeners.push(operands[1]);
}
} else {
nextTick(function () {
resolvedPromise.promiseDispatch.apply(resolvedPromise, args);
});
}
};
// XXX deprecated
promise.valueOf = function () {
if (messages) {
return promise;
}
var nearerValue = nearer(resolvedPromise);
if (isPromise(nearerValue)) {
resolvedPromise = nearerValue; // shorten chain
}
return nearerValue;
};
promise.inspect = function () {
if (!resolvedPromise) {
return { state: "pending" };
}
return resolvedPromise.inspect();
};
if (Q.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
// NOTE: don't try to use `Error.captureStackTrace` or transfer the
// accessor around; that causes memory leaks as per GH-111. Just
// reify the stack trace as a string ASAP.
//
// At the same time, cut off the first line; it's always just
// "[object Promise]\n", as per the `toString`.
promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
}
// NOTE: we do the checks for `resolvedPromise` in each method, instead of
// consolidating them into `become`, since otherwise we'd create new
// promises with the lines `become(whatever(value))`. See e.g. GH-252.
function become(newPromise) {
resolvedPromise = newPromise;
promise.source = newPromise;
array_reduce(messages, function (undefined, message) {
nextTick(function () {
newPromise.promiseDispatch.apply(newPromise, message);
});
}, void 0);
messages = void 0;
progressListeners = void 0;
}
deferred.promise = promise;
deferred.resolve = function (value) {
if (resolvedPromise) {
return;
}
become(Q(value));
};
deferred.fulfill = function (value) {
if (resolvedPromise) {
return;
}
become(fulfill(value));
};
deferred.reject = function (reason) {
if (resolvedPromise) {
return;
}
become(reject(reason));
};
deferred.notify = function (progress) {
if (resolvedPromise) {
return;
}
array_reduce(progressListeners, function (undefined, progressListener) {
nextTick(function () {
progressListener(progress);
});
}, void 0);
};
return deferred;
}
主要是最底层的方法deferred.notify
。
示例用法:
function requestOkText(url) {
var request = new XMLHttpRequest();
var deferred = Q.defer();
request.open("GET", url, true);
request.onload = onload;
request.onerror = onerror;
request.onprogress = onprogress;
request.send();
function onload() {
if (request.status === 200) {
deferred.resolve(request.responseText);
} else {
deferred.reject(new Error("Status code was " + request.status));
}
}
function onerror() {
deferred.reject(new Error("Can't XHR " + JSON.stringify(url)));
}
function onprogress(event) {
deferred.notify(event.loaded / event.total);
}
return deferred.promise;
}
requestOkText("http://localhost:3000")
.then(function (responseText) {
// If the HTTP response returns 200 OK, log the response text.
console.log(responseText);
}, function (error) {
// If there's an error or a non-200 status code, log the error.
console.error(error);
}, function (progress) {
// Log the progress as it comes in.
console.log("Request progress: " + Math.round(progress * 100) + "%");
});
我灵感来自 Gil 和 Travis 的答案,提出了一个解决方案,它用更接近 Q 实现的方法装饰了 Promise 构造函数。
请注意,此装饰依赖于Promise.$$state
. 这是为 Angular 1.6.4 构建的,理论上应该可以一直工作到 1.3.x,但不能保证该版本或将来的版本:
(function() {
'use strict';
angular
.module('your.module.name.goes.here')
.config(configBlock);
/** @ngInject */
configBlock.$inject = ['$provide'];
function configBlock($provide) {
$provide.decorator('$q', ['$delegate', function ($delegate) {
console.log($delegate);
var Promise = $delegate.prototype.constructor;
Promise.prototype.inspect = function () {
var inspect = {};
switch (this.$$state.status) {
case -1:
case 0:
inspect.state = 'pending';
break;
case 1:
inspect.state = 'fulfilled';
break;
case 2:
inspect.state = 'rejected';
break;
default:
inpsect.state = 'unknown';
}
return inspect;
};
Promise.prototype.isFulfilled = function () {
return this.inspect().state === 'fulfilled';
}
Promise.isFulfilled = function (obj) {
if (obj.constructor !== Promise) {
return true;
}
return obj.isFulfilled();
}
Promise.prototype.isRejected = function () {
return this.inspect().state === 'rejected';
}
Promise.isRejected = function (obj) {
if (obj.constructor !== Promise) {
return false;
}
return obj.isRejected();
}
Promise.prototype.isPending = function () {
return this.inspect().state === 'pending';
}
Promise.isPending = function (obj) {
if (obj.constructor !== Promise) {
return false;
}
return obj.isPending();
}
return $delegate;
}]);
}
})();