我如何在这个ES6 JS代码中进行Promise链接

时间:2017-08-17 01:22:27

标签: javascript es6-promise

我刚刚从一家名为Canva的公司获得了我的采访结果。其中一个反馈是我应该在下面的代码中使用Promise链接。当只涉及一个Promise时,我无法理解如何进行任何链接(aTeam.setTeam()返回一个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));
    })
}

请告诉我如何在这里做Promise链接。

我的完整代码位于Canva's Tournament Challenge interview question

1 个答案:

答案 0 :(得分:0)

看看你的代码,似乎你正在包装你的承诺,我所采取的是他们的意思" chaining"。

你这样做:

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

你不需要包装它们,只需返回承诺:

return someOtherPromise;

例如,您的getTeam功能可能只是:

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