我有以下代码(Angular 6),当将promise转换为可观察对象并使用管道和地图/ switchMap传播时,该代码有效:
import { Observable, of, from as observableFrom } from 'rxjs';
public initialise(): Observable<boolean> {
return observableFrom(SomeExternalSDK()).pipe( // where SomeExternalSDK() is a promise
map(response => {
this.lib = response;
}),
switchMap(() => this.lib.CreateMyTable()), // CreateMyTable() is a promise
switchMap(() => this.lib.UpdateData()), // UpdateData() is a promise
map(() => {
console.log('initialised!!');
return true;
}),
catchError(error => {
console.log('error: ' + error);
return of (false);
})
);
}
但是,为了更好地了解异步/等待,我想将其转换为:
public initialise(): Observable<boolean> {
const doInit = async () => {
try {
this.lib = await SomeExternalSDK(); // errors out on this line.
await this.lib.CreateMyTable();
await this.lib.UpdateData();
console.log('initialised!!');
return true;
} catch (error) {
console.log(error);
return false;
}
};
return observableFrom(doInit());
}
但是在运行代码时,在等待SomeExternalSDK()调用时,它似乎会导致错误,但try / catch并没有捕获该错误,并且控制台中没有任何有用的东西。 我在这里做错什么明显吗?我不习惯在打字稿中等待/异步,所以只是想弄清楚这个东西。