gpt4 book ai didi

Javascript:如何使用 observable 并行调用多个 Promise 函数?

转载 作者:行者123 更新时间:2023-11-28 14:18:10 25 4
gpt4 key购买 nike

我有多个 promise 函数:

function test1(){
const numberPromise = new Promise((resolve) => {
resolve(1);
});
return numberPromise;
}

function test2(){
const numberPromise = new Promise((resolve) => {
resolve(2);
});
return numberPromise;
}

function test3(){
const numberPromise = new Promise((resolve) => {
resolve(3);
});
return numberPromise;
}

我想将其称为并行,就像 Promise.all([test1(),test2(),test3()]) 但我不想使用 Promise,我想使用可观察

为了完成这个任务,我正在这样做:

import { Observable } from 'rxjs/Observable';
var data=Observable.of(test1(),test2(),test3());
data.subscribe((data)=>{
console.log("data :",data);
})

但我得到的结果如下: enter image description here

但我想得到这样的:

data :1
data :2
data :3



[1]: /image/0wamC.png

最佳答案

尝试使用forkjoin

const example = forkJoin(
//emit 'Hello' immediately
of('Hello'),
//emit 'World' after 1 second
of('World').pipe(delay(1000)),
//emit 0 after 1 second
interval(1000).pipe(take(1)),
//emit 0...1 in 1 second interval
interval(1000).pipe(take(2)),
//promise that resolves to 'Promise Resolved' after 5 seconds
myPromise('RESULT')
);
//output: ["Hello", "World", 0, 1, "Promise Resolved: RESULT"]
const subscribe = example.subscribe(val => console.log(val));

Example here .

关于Javascript:如何使用 observable 并行调用多个 Promise 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56526015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com