Javascript 序列化可观察的下一个函数调用
考虑以下Typescript/rxjs代码:Javascript 序列化可观察的下一个函数调用,javascript,typescript,rxjs,Javascript,Typescript,Rxjs,考虑以下Typescript/rxjs代码: import { range } from 'rxjs'; range(1, 5).subscribe(async (num) => { await longLastingOperation(num); }) function longLastingOperation(num) { console.log('starting', num); return new Promise((resolve) => { s
import { range } from 'rxjs';
range(1, 5).subscribe(async (num) => {
await longLastingOperation(num);
})
function longLastingOperation(num) {
console.log('starting', num);
return new Promise((resolve) => {
setTimeout(() => {
console.log('done with', num);
resolve();
}, Math.random() * 1000);
});
}
每个发出的值都会触发随机持续时间的长时间操作。控制台输出是不可预测的,看起来与此类似:
starting 1
starting 2
starting 3
starting 4
starting 5
done with 2
done with 5
done with 1
done with 4
done with 3
现在,我想“序列化”每个发出值的长期操作的执行。例如,我希望longLastingOperation(2)
在开始之前等待longLastingOperation(1)
完成
我希望每次都能获得这样的输出:
starting 1
done with 1
starting 2
done with 2
starting 3
done with 3
starting 4
done with 4
starting 5
done with 5
使用rxjs和Observable如何实现这一点?考虑在每个
longLastingOperation(num)
调用上使用concatMap
操作符,以将响应包装在Observable中,并按顺序订阅结果:
range(1, 5)
.concatMap((num) => {
return Observable.fromPromise(longLastingOperation(num));
})
.subscribe(res => {
console.log(`End working on ${res}`) // Shall be ordered here
})
以下是文档参考:以下是我在这个主题上的一些额外工作:
考虑在每个
longLastingOperation(num)
调用上使用concatMap
操作符,将响应包装为可观察,并按顺序订阅结果:
range(1, 5)
.concatMap((num) => {
return Observable.fromPromise(longLastingOperation(num));
})
.subscribe(res => {
console.log(`End working on ${res}`) // Shall be ordered here
})
以下是文档参考:以下是我在这个主题上的一些额外工作:
很高兴我能帮忙。请查看并在
部分选择一个操作员
,以供参考。它将指出95%的情况下您需要的操作员。不幸的是,RxJS 6在其文档站点上没有此功能:(很高兴我能够提供帮助。请查看并在部分选择一个操作员以供参考。它将指出95%的情况下您需要的操作员。不幸的是,RxJS 6在其文档站点上没有此功能:(