Search code examples
javascripttypescriptpromisees6-promise

How to return promise?


I have a function

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;
}

How to return the result to promise, I tried my best, But I don't know to do t, Maybe its because of two observable I have inside of it,


Solution

  • You would promisify both observables, and then use Promise.all to get a promise that fulfils when all is done:

    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));
    }
    

    Now you don't store the result in this.result, but make it the promised value, which you get like this:

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

    You could of course still store the result in this.result, but that would not be best practice as it suggests that a piece of code may try to access it before it is available: you would always use the then method to get to the result.