我刚刚从一家名为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链接。
答案 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();
}