简体   繁体   English

ES6中的Angular中的$ q或Promises

[英]$q in Angular or Promises in ES6

I have a project using ES6 and AngularJS, and as far as I found, AngularJS $q promises is synchronous but ES6 promises not. 我有一个使用ES6和AngularJS的项目,据我发现,AngularJS $ q承诺是同步的,但ES6承诺不是。 Right? 对? The question is, what are the differences? 问题是,有什么区别? and when should I use $q or ES6? 什么时候应该使用$ q或ES6? I know what is the difference between Synchronous and Asynchronous, but got confused between new Promise and AngularJS $q . 我知道Synchronous和Asynchronous之间有什么区别,但是在new PromiseAngularJS $q之间感到困惑。

raise from here 这里升起

The statement about $q synchronicity applies to unit tests with ngMock in the first place. 有关$q同步性的声明首先适用于ngMock单元测试。

$q promises are capable of being synchronous in production: $q promises 可以在生产中同步:

let foo;

$q.resolve().then(() => { foo = 1 });
$rootScope.$digest();
console.log(foo === 1);

And they are supposed to be synchronous in unit tests, because all AngularJS services that are responsible for asynchronous behaviour ( $timeout , $http , etc) are mocked with ngMock in order to make tests fully synchronous: 而且它们应该在单元测试中是同步的,因为所有负责异步行为的AngularJS服务( $timeout$http等)都被ngMock模拟,以使测试完全同步:

it('...', inject(($q) => {
    let foo;

    $q.resolve().then(() => { foo = 1 });
    $rootScope.$digest();
    expect(foo).toBe(1);
}));

While ES6 promises are asynchronous by design, and then callback runs on next tick: 虽然ES6 Promise在设计上是异步的, then回调在下一个刻度运行:

it('...', (done) => {
    let foo;

    Promise.resolve(1).then(() => {
      foo = 1;
      expect(foo).toBe(1);
    })
    .then(done, done.fail);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM