代码之家  ›  专栏  ›  技术社区  ›  otto

如何在另一个函数中解析异步函数?

  •  0
  • otto  · 技术社区  · 4 年前

    你好我有这个功能:

      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…
    
    0 回复  |  直到 4 年前
        1
  •  1
  •   hackape    4 年前

    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)
      }