【问题标题】:How to return the value resolved from promise in function?如何在函数中返回从 promise 解析的值?
【发布时间】:2021-11-28 12:13:57
【问题描述】:

文件1.ts: 我正在调用 file2 服务的以下方法并期待响应。

const output = await this.file2Service.getMainData();

文件2.ts: 我期待以下方法的返回值(数据源)。但是这里发生的是“下面的函数甚至在 .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;

}

请忽略上面sn-p中的语法错误,它只是一个例子而不是实际代码。

【问题讨论】:

  • 两个问题,第一个是将async/await 与promise .then 方法混淆,选择一个模式并坚持下去。第二个是你期望返回什么?从当前的尝试来看,您似乎想返回最后一个成功的结果,但是有一个结果数组,这是您想要的吗?
  • @Matthew 是的,我正在尝试返回 if () 块中存在的值。
  • this.getSubData() 是否返回一组承诺?另一个问题是dataSource 不存在于getMainData 的最外层范围内。需要更好地了解问题。谢谢!

标签: javascript angular typescript async-await es6-promise


【解决方案1】:

如果您已经在等待某个方法,则无需调用 .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.');
}

【讨论】:

    猜你喜欢
    • 2015-10-17
    • 2020-03-28
    • 1970-01-01
    • 2017-11-01
    • 2021-06-03
    • 2021-09-03
    • 2017-04-08
    • 1970-01-01
    • 2020-06-24
    相关资源
    最近更新 更多