gpt4 book ai didi

javascript - 如何返回 promise ?

转载 作者:行者123 更新时间:2023-12-03 03:28:36 27 4
gpt4 key购买 nike

我有一个函数

parseJobs(userId: string) {
this.getLikedJobs(userId).subscribe(result => {
result.map(key =>{
let rows = {
name : (key as any).jobsUser.firstName,
jobType: 'Liked'
}
let job = {...rows,...(key as any).jobPosting};
this.result.push(job);
});
});

this.getSavedJobs(userId).subscribe(result => {
result.map(key =>{
let rows = {
name : (key as any).jobsUser.firstName,
jobType: 'Saved'
}
let job = {...rows,...(key as any).jobPosting};
this.result.push(job);
});
});
return this.result;
}

如何将结果返回给promise,我尽力了,但我不知道该怎么做,也许是因为我里面有两个可观察的,

最佳答案

您将 Promisify 两个可观察量,然后使用 Promise.all 来获得在所有操作完成后实现的 Promise:

parseJobs(userId: string) {
// Create a promise
const p1 = new Promise(resolve => {
this.getLikedJobs(userId).subscribe(result => {
// Resolve with the modified array
resolve(result.map(key =>{
let rows = {
name : (key as any).jobsUser.firstName,
jobType: 'Liked'
}
let job = {...rows,...(key as any).jobPosting};
// In a map, you want to return:
return job;
}));
});
});
// Same here:
const p2 = new Promise(resolve => {
this.getSavedJobs(userId).subscribe(result => {
resolve(result.map(key =>{
let rows = {
name : (key as any).jobsUser.firstName,
jobType: 'Saved'
}
let job = {...rows,...(key as any).jobPosting};
return job;
}));
});
});
// Return a promise that will fulfill when both promises fulfill
// and concatenate the results
return Promise.all([p1, p2]).then(result => [].concat(...result));
}

现在,您不再将结果存储在 this.result 中,而是将其设为 promise 值,如下所示:

parseJobs(1).then(result =>
console.log(result);
});

您当然仍然可以将结果存储在 this.result 中,但这不是最佳实践,因为它表明一段代码可能会在它可用之前尝试访问它:您会始终使用 then 方法获取结果。

关于javascript - 如何返回 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46193304/

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