因为它返回一个Promise,所以将一个await添加到_personService.getPersonById中。
只有在前面的等待完成后才能命中console.log。
public async ngOnInit() {
await this._personService.getPersonById(personId)
.then(person => this.person = person)
.catch(err => console.log(err));
console.log(this.person);
if (this.person) {
await this._teamService.getTeamById(this.person.teamId)
.then(teamData => this.team = teamData)
.catch(err => {
// note curlys allow multiple statments.
// do work with error, log it etc..
}
}
}
至于为什么你看到HTML中的价值,而不是控制台。 HTML数据绑定只要有值,就会显示Promise的结果。 console.log在getPersonById后立即被调用(某些ms),当不等待时,它在那个时刻没有值。
这是通过嵌套函数来完成上述操作的。请注意0。
public async ngOnInit() {
await this._personService.getPersonById(personId)
.then(async person => {
// To Use await inside .then, add async like above
this.person = person;
await this._teamService.getTeamById(this.person.teamId)
.then(teamData => this.team = teamData)
.catch(err => console.log(err));
})
.catch(err => console.log(err));
console.log(this.person);
当你调用返回一个承诺的功能,当时将首次承诺解决后调用。而随后.thens(你可以将它们添加)。 thens总是同步运行。太多这被称为“链”,被认为是不好的设计。无论您是否在等待,Thens都是顺序/同步的。
如果您希望outter函数等待(或“阻止”),以便同步运行,您也可以等待它们。
最后编辑: 我建议使用以下从其他SO answer复制了解async/await。
使用:
public delay(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
呼叫以下并注意输出的顺序。增加和变更等待,以了解它的行为。
public async someFcn() {
console.log('1');
this.delay(2000)
.then(x => console.log('2'));
console.log(3)
await this.delay(1000)
.then(x => console.log('4')
.then(x => console.log('5');
console.log('Done');
}
谢谢你的解释,我也尝试如下,并将其错误,“无法读取的未定义的属性‘teamId’”,因为输入值“this.person.teamId”不可用。 this._teamService.getTeamById(this.person.teamId) .then(teamData => {if(this.person!== undefined){this。team = teamData; }}); –
我无法想到可以避免回调问题的其他选择,任何帮助将不胜感激。 –
谢谢。我添加了“console.log”来检查this.person.teamId值,因为我在浏览器开发人员工具上发生错误为“Can not read property'teamId'”。我已经添加了等待,因为你演示了它,它给了我一个编译错误,因为“无法找到名字等待”我是ANgular2的新手,请你纠正我。谢谢 –