问题
AngularJS promises seem to be tied to a digest cycle, as in, the success/error callbacks are not called until a digest cycle is run. This means that anything that uses promises, such as $http
or manually created promises, also need to trigger a digest cycle in order to get the callbacks to run.
Is it possible to use promises in Angular, without the digest cycle being run at all? I realise you can use $applyAsync
, which schedules the digest cycle for a bit later, but I'm looking to not run the digest cycle at all, and still have the then
callbacks run.
Essentially I'm trying to work out how to squeeze as much performance as possible from an app that would use a fair bit of asynchronous behaviour that would need promises resolved but not necessarily the digest cycle run.
回答1:
No, it is currently not possible. Whenever a then
handler runs it schedules the callback via $evalAsync
which schedules a digest if one is not already scheduled.
The exception to this is $timeout
that accepts an extra argument to not run a digest. On the other hand - multiple promises that resolve in the same turn run on the same digest.
Your options are:
- Use XMLHttpRequqest directly, seriously - it's not very hard. The biggest downside to this is that it will not respect interceptors and other $http hooks (like the mock backend).
- Decorate $q
to not schedule via $evalAsync
or add a .thenNoDigest
method to the promise prototype that schedules via setTimeout
.
- Use a userland promise library instead of $q for $http or over XHR.
来源:https://stackoverflow.com/questions/29428629/resolving-promises-without-a-digest-cycle