[RxJS] firstValueFrom/lastValueFrom (convert observable to promise)
Converts an observable to a promise by subscribing to the observable, and returning a promise that will resolve as soon as the first value arrives from the observable. The subscription will then be closed.
WARNING: Only use this with observables you know will emit at least one value, OR complete. If the source observable does not emit one value or complete, you will end up with a promise that is hung up, and potentially all of the state of an async function hanging out in memory. To avoid this situation, look into adding something like timeout
, take
, takeWhile
, or takeUntil
amongst others.
import { interval, firstValueFrom } from 'rxjs';
async function execute() {
const source$ = interval(2000);
const firstNumber = await firstValueFrom(source$);
console.log(`The first number is ${ firstNumber }`);
}
execute();
// Expected output:
// 'The first number is 0'
lastValueFrom
import { interval, take, lastValueFrom } from 'rxjs';
async function execute() {
const source$ = interval(2000).pipe(take(10));
const finalNumber = await lastValueFrom(source$);
console.log(`The final number is ${ finalNumber }`);
}
execute();
// Expected output:
// 'The final number is 9'
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-02-11 [Bash] Read and Use JSON in Bash with jq
2021-02-11 [Bash] Set Default Arguments with Bash Shell Parameter Expansions
2021-02-11 [Bash] Shortcut
2021-02-11 [Bash] Rerun Bash Commands with History Expansions (!! & !$)
2021-02-11 [Bash] Create and Copy Multiple Files with Brace Expansions in Bash
2021-02-11 [Bash] Add Executable Files to $PATH with Bash
2019-02-11 [HTML5] Add an SVG Image to a Webpage and Get a Reference to the Internal Elements in JavaScript