javascript - ForEach is faster than my Observable returns values -
i have following code:
evaluatelocations() { const locs = this.currenttour.locids; let lastloc = null; locs.foreach(loc => { console.log(lastloc, loc); if (lastloc !== null) { console.log('if durch', lastloc, loc); this.afdb.list('routes', { query: { orderbychild: 'idstart', equalto: loc } }).switchmap(items => { console.log('switchmap starts', lastloc, loc); //here output lastloc = loc while shouldn't const filtered = items.filter(item => item.idend === lastloc); const route = filtered[0]; return observable.of(route); }).subscribe(); } lastloc = loc; }); } now, @ point switchmap comes play, foreach loop seems have run through filtering done wrong.
my logic is:
want loop through array of ids. call database gets entries starting point locs[n]. want filter locs[n+1] , return 1 result.
in theory should work, given query firebase database, observable has time lag in there , cannot values enough. thing suspect , read fact observables might cancelled if 1 started before current 1 finished. when run code not seem problem.
if want work list sequentially, need wait operation of observable finish. idiomatic way seems be converting observable promise , await that:
applying code:
async evaluatelocations() { // <-- make method async, can use await const locs = this.currenttour.locids; let lastloc = null; (let lockey in locs) { // <-- use regular for-in loop let loc = locs[lockey]; console.log(lastloc, loc); if (lastloc !== null) { console.log('if durch', lastloc, loc); await this.afdb.list('routes', { // <-- use await here query: { orderbychild: 'idstart', equalto: loc } }).switchmap(items => { console.log('switchmap starts', lastloc, loc); //here output lastloc = loc while shouldn't const filtered = items.filter(item => item.idend === lastloc); const route = filtered[0]; return observable.of(route); }).topromise(); // <-- convert promise } lastloc = loc; } } don't forget need await evaluatelocations() in calling function, if need afterwards relies on outcome of evaluatelocations().
Comments
Post a Comment