gpt4 book ai didi

angular - 如何让执行等待 forkJoin 结果

转载 作者:搜寻专家 更新时间:2023-10-30 21:29:16 27 4
gpt4 key购买 nike

如何让以下代码等待 forkJoin 执行,以便我可以从 bulkRequest 返回结果?

  constructor(private http: Http) {
let results = this.bulkRequest(this.get("https://jsonplaceholder.typicode.com/posts/1"),
this.get("https://jsonplaceholder.typicode.com/posts/1"),
this.get("https://jsonplaceholder.typicode.com/posts/1"));

console.log("results");
}

get(url: string): Observable<any> {
return this.http.get(url).map(response => response.json());
}

bulkRequest(...sources: SubscribableOrPromise<any>[]): any[] {
let results: any[];

Observable.forkJoin(
sources
).subscribe(response => {
console.log("responses");
results = response;
}, error => {
console.log("error: " + error.toString());
},
() => {
console.log("finally");
});

return results;
}

目前我得到以下控制台输出并且 results 变量是 undefined:

results
responses
finally

Observable 会执行,如果我在 console.log("results") 行中放置一个断点,我会在 Network 选项卡中将它们全部视为 Pending

请联系:http://plnkr.co/edit/2wb72kw7S3wYUUwwwi8h?p=preview

最佳答案

return Observable.forkJoin( ...

并移除

return results;

无法等待可观察对象。您需要在调用 bulkRequest() 的地方订阅返回的 observable。

关于angular - 如何让执行等待 forkJoin 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459061/

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