【问题标题】:How to resolve async function inside another function? [duplicate]如何在另一个函数中解析异步函数? [复制]
【发布时间】:2021-01-08 20:07:10
【问题描述】:

你好我有这个功能:

  const getImageSize = (url) => {
    const img = new Image()
    img.src = url
    return img.onload = async function() {
      
      return{
        height: this.height,
        width: this.width,
        scale: parseInt(this.height / this.width)
      }
    }
    
  }

我这样称呼它

  const test = async () =>{
    const imageSize = await getImageSize(data[0].image.url)
    console.log(imageSize)
  }

我得到了函数本身,但没有得到值。 我该如何解决这个问题?

这是日志:

ƒ () {
    var self = this,
        args = arguments;
    return new Promise(function (resolve, reject) {
      var gen = fn.apply(self, args);

      function _next(value) {
        asyncGeneratorStep…

【问题讨论】:

  • 您需要使用明确的承诺 (new Promise) 而不是 async 关键字来解决此问题。

标签: javascript reactjs ecmascript-6 async-await


【解决方案1】:

async 只是Promise 的语法糖。对于这种情况,您可以返回如下承诺:

  const getImageSize = (url) => {
    const img = new Image()
    img.src = url
    let resolve
    img.onload = function() {
      resolve({
        height: this.height,
        width: this.width,
        scale: parseInt(this.height / this.width)
      })
    }

    return new Promise(r => resolve = r)
  }

【讨论】:

  • 谢谢这个作品。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-18
  • 2019-05-01
  • 2019-09-26
  • 1970-01-01
相关资源
最近更新 更多