I'm having some trouble to figure out why my await statement is not respected and code proceeds before the completion the async function.
My code:
async getSensors(boardId: number): Promise<Sensor[]> {
console.log('call sensor');
const sensors: Sensor[] = [];
await this.http.get<object[]>(API_URL + 'sensors/' + boardId).toPromise().then(res => {
console.log('http sensor');
res.forEach(r => sensors.push(GenericDeserialize(r, Sensor)));
});
console.log('return sensor');
return sensors;
}
async getRelays(boardId: number): Promise<Relay[]> {
console.log('call relay');
const relays: Relay[] = [];
await this.http.get<object[]>(API_URL + 'relays/' + boardId).toPromise().then(res => {
console.log('http relay');
res.forEach(r => relays.push(GenericDeserialize(r, Relay)));
});
console.log('return relay');
return relays;
}
async getBoards(): Promise<Board[]> {
const boards: Board[] = [];
await this.http.get<object[]>(API_URL + 'boards').toPromise().then(async res => {
console.log('http boards');
await res.forEach(async b => {
console.log('loop', b);
const board = GenericDeserialize(b, Board);
await this.getSensors(board.boardId).then(sensors => board.sensors = sensors);
await this.getRelays(board.boardId).then(relays => board.relays = relays);
boards.push(board);
});
});
console.log('return boards');
return boards;
}
My jasmine test:
it('should have two sensors and one relay', async () => {
const service: DataService = TestBed.get(DataService);
const boards = await service.getBoards();
const board = boards[0];
expect(board.sensors.length).toBe(2);
expect(board.relays.length).toBe(1);
});
This is the actual "callstack" that the console outputs when I run my test:
'return relay'
'http relay'
'return relay'
'http boards'
'loop', Object{board_id: 0, board_name: 'test'}
'call sensor'
'loop', Object{board_id: 1234, board_name: 'esp1'}
'call sensor'
'return boards'
And this is the "callstack" that I was expecting:
'http boards'
'loop', Object{board_id: 0, board_name: 'test'}
'call sensor'
'http sensor'
'return sensor'
'call relay'
'http relay'
'return relay'
'loop', Object{board_id: 1234, board_name: 'esp1'}
'call sensor'
'http sensor'
'return sensor'
'call relay'
'http relay'
'return relay'
'return boards'