[英]How to return the value resolved from promise in function?
File1.ts:我正在調用 file2 服務的以下方法並期待響應。
const output = await this.file2Service.getMainData();
File2.ts:我期待以下方法的返回值(dataSource)。 但是這里發生的是“下面的 function 甚至在代碼 in.then() 塊執行之前就返回了數據源。”
所以我每次都變得不確定。 需要做什么才能獲得實際的 dataSource 值。
public async getMainData(): Promise<any> {
const data = await this.getSubData();
data.forEach((result) => {
result.then((finalResult) => {
if (finalResult === 'success') {
const dataSource = await this.callDataSource();
}
});
});
return dataSource;
}
請忽略上面代碼段中的語法錯誤,它只是一個示例,不是實際代碼。
如果您已經在等待方法,則無需調用.then
。
public async getMainData(): Promise<any> {
const data = await this.getSubData();
for (const result of data) {
// from your code sample it's unclear
// whether getSubData returns a collection of
// values or a collection of promises-of-values,
// remove the await if you're simply returning values
const finalResult = await result;
if (finalResult === 'success') {
return await this.callDataSource();
}
}
throw new Error('could not find a successful result.');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.