如何 return 从函数中的 promise 解析的值?
How to return the value resolved from promise in function?
File1.ts:
我正在调用 file2 服务的以下方法并期待响应。
const output = await this.file2Service.getMainData();
File2.ts:
我期待来自以下方法的 return value(dataSource)。但是这里发生的是“下面的函数甚至在 .then() 块中的代码被执行之前 returning 数据源。”
所以我每次都变得不确定。需要做什么才能获得实际的数据源值。
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.');
}
File1.ts: 我正在调用 file2 服务的以下方法并期待响应。
const output = await this.file2Service.getMainData();
File2.ts: 我期待来自以下方法的 return value(dataSource)。但是这里发生的是“下面的函数甚至在 .then() 块中的代码被执行之前 returning 数据源。”
所以我每次都变得不确定。需要做什么才能获得实际的数据源值。
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.');
}