Amarsh Amarsh - 1 month ago 15
Javascript Question

How do I do Promise chaining in this ES6 JS code

I just got my interview results back from a company called Canva. One of the feedback was that I was supposed to use Promise chaining in the following code. I am unable to comprehend how to do any chaining when there is only one Promise involved (

returns a Promise)

return new Promise((resolve, reject) => {
// we first scan to see if the team has been initialized already. if so, we resolve immediately
if(this.teams[teamId]) return resolve(this.teams[teamId]);
// if not, we create a new Team, cache it, and issue a request to the server to set it
let aTeam = new Team(this,teamId); this.teams[teamId] = aTeam;

Please advise me how would I do Promise chaining here.

My complete code is at Canva's Tournament Challenge interview question.

Answer Source

Looking at your code, it seems you are wrapping your promises, which I take is what they mean by "chaining".

You do:

return new Promise((resolve, reject){
    someOtherPromise.then(r => resolve(r), err => reject(err));

You don't need to wrap them, just return the promise:

return someOtherPromise;

For example, your getTeam function could simply be:

       return Promise.resolve(this.teams[teamId]);
    let aTeam = new Team(this,teamId);
    this.teams[teamId] = aTeam;
    return aTeam.setTeam();