我想知道这两种方法在Angular框架中处理异步调用的区别。
如果没有,它们有什么区别,我到底什么时候可以使用一个而不是另一个?谢谢:)我想知道这两种方法在Angular框架中处理异步调用时的区别。
第一种方法的 async/await
是库存的JavaScript,你想异步运行函数,你可以等待承诺,然后再转到下一行。
it('it block in an async await way', async(done) => {
await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
// do something, make assertions
const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
// do something, make assertions
done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});
脚本中的 fixture.whenStable
基本上是等待堆栈中所有的承诺被解决后再进行断言。
it('demonstration of fixture.whenStable', async(done) => {
// do some actions that will fire off promises
await fixture.whenStable(); // wait until all promises in the call stack have been resolved
// do some more assertions
done(); // call done to tell Jasmine you're done with this test.
});
done回调是可选的,但我使用它是为了确保更好的工程设计(确保它遍历了整个it块)。
编辑 ==========================================================================================
为了处理观测值,我使用了两种方法。
async/await
用 take
和 toPromise
操作符,在这里你把第一个排放转换成一个承诺。欢迎添加其他运算符,如 filter
忽略一些排放,然后再进行 take(1)
.
import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
const x = await component.observable$.pipe(take(1)).toPromise();
expect(x).toBe(....);
done();
});
另一种方法是 subscribe
与 done
回调
it('should do xyz', done => {
component.observable$.subscribe(result => {
expect(result).toBe(...);
// call done here to ensure the test made it within the subscribe
// and did the assertions and to let Jasmine know you're done with the tests
done();
});
});