【问题标题】:Can't access an async function's response无法访问异步函数的响应
【发布时间】:2019-07-25 02:28:40
【问题描述】:

我似乎找不到从异步值访问值的方法,因为它总是返回未定义,我想等待函数结束然后检索该值,但它不起作用...

  async UploadFile(file): Promise<any> {

      let ipfsId: any
      const fileStream = fileReaderPullStream(file)
      await this.ipfs.add(fileStream, { progress: (prog) => console.log(`received: ${prog}`) })
      .then((response) => {
        ipfsId = response[0].hash
        console.log(ipfsId)
        return ipfsId
        //window.open("localhost:8080/ipfs/" + ipfsId);
        //window.open("https://ipfs.io/ipfs/" + ipfsId);
      }).catch((err) => {
        console.error(err)
      }) 

  }

这是我的电话:

  uploadFile(event) {

    const fileSelected: File = event.target.files[0];
    (async() => {
    this.temp_ipfs_hash = await this.IPFS.UploadFile(fileSelected)
    .then((response) => console.log(response))
    console.log(this.temp_ipfs_hash)
    })()

  }

我想访问返回值,但它总是返回未定义或错误值... 有人知道我可以在这里尝试什么吗?

非常感谢您抽出宝贵时间! :)

编辑:我不知道发布图片是错误的,很抱歉,我已经更改了!对不起! :(

【问题讨论】:

  • 总是发布你的代码而不是添加图片
  • 更准确地说,将您的代码发布为文本,以便用户能够轻松地复制/粘贴它。请参阅this guide 格式化代码块
  • 我已经改了,很抱歉,我不知道:(

标签: angular typescript asynchronous ipfs


【解决方案1】:

您同时使用基于 then 的 promise 和 async await,您的上传文件函数应该返回一个 promise,然后适当地解决拒绝它,或者如果您想坚持 async-await 机制,那么您的上传文件函数将不得不更改.以下是应该如何使用 async await,假设 foobar 是一个异步函数,如您的 ipfs.add

async function foo() {
  let results = await foobar();
  return results;
}

这就是你如何称呼这样的 foo

async function bar() {
  let fooResults = await foo();
  console.log(fooResults);
}

【讨论】:

  • 这样完美运行,我不知道它会这样运行,非常感谢!! :)
【解决方案2】:
  • UploadFile 应该返回一个承诺,它目前什么也没返回。 为了链接承诺,您应该将最后一行替换为

    return this.ifps.add(...).then(...).catch(...);


  • 使用await的替代方法:return await,即promise返回的结果值

    return await this.ifps.add(...).then(...).catch(...);

    在调用者中,你可以像没有承诺一样记录结果:

    console.log(this.UploadFile(fileSelected));

【讨论】:

    猜你喜欢
    • 2021-04-04
    • 1970-01-01
    • 2023-01-25
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-11
    • 1970-01-01
    相关资源
    最近更新 更多