0

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 ( aTeam.setTeam() returns a Promise)

getTeam(teamId){
    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;
        aTeam.setTeam().then(()=>resolve(aTeam)).catch((err)=>reject(err));
    })
}

Please advise me how would I do Promise chaining here.

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

MinusFour
  • 13,913
  • 3
  • 30
  • 39
Amarsh
  • 11,214
  • 18
  • 53
  • 78
  • Read: [Promise chaining](https://javascript.info/promise-chaining) – Gerardo Aug 17 '17 at 01:30
  • No, you're not supposed to do promise chaining here. You just should avoid using the `new Promise` constructor. – Bergi Aug 17 '17 at 02:00
  • What does the `setTeam` promise resolve with? – Bergi Aug 17 '17 at 02:01
  • setTeam returns a new Promise() – Amarsh Aug 17 '17 at 02:45
  • setTeam returns a new Promise() and it resolves to nothing, I mean, it just goes resolve(). Team is a class, and setTeam() is supposed to make an asynch call and set itself up after it has been instantiated. Thanks to yours and MinusFour's answers, I understand what is wrong (I doubt the assessor had meant this though) – Amarsh Aug 17 '17 at 02:56

1 Answers1

0

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:

getTeam(){
    if(this.teams[teamId]){
       return Promise.resolve(this.teams[teamId]);
    }
    let aTeam = new Team(this,teamId);
    this.teams[teamId] = aTeam;
    return aTeam.setTeam();
}
MinusFour
  • 13,913
  • 3
  • 30
  • 39
  • Aah thanks, I understand it now. setTeam() should return a Promise that would resolve to 'this' , ie the object which has been configured as a result of the asynch call that setTeam() makes. This has nothing to do with Promise chaining though. Its more like the situation try{} catch(err) {throw new Error(err)} . Thanks for clarifying. – Amarsh Aug 17 '17 at 02:57