js函数返回值赋予变量,函数还没执行完,变量已经赋值

var arrPicture11 = util.redraw(that.data.src, that.data.screenWidth, that.data.screenHeight, that.data.rectanglesBeginx, that.data.rectanglesBeginy, that.data.rectanglesWidth, that.data.rectanglesHeight)
    console.log(arrPicture11)

已下是封装的函数

function redraw(imgSrc, screenWidth, screenHeight,theBeginx,theBeginy,theWidth,theHeight){
  wx.getImageInfo({
    src: imgSrc,
    success: function (res) {
      // 判断图的长
      if (res.height <= 1096) {
        var h = screenWidth * res.height / res.width;
        var beginy = (screenHeight - h - 119) / 2;
        var w = screenWidth;
        var beginx = 0;
        if (beginy < 0) {
          beginy = 0;
        }
      } else {
        var w = (screenHeight-119) * res.width / res.height;
        var beginx = (screenWidth - w) / 2;
        var h = (screenHeight-119);
        var beginy = 0;
        if (beginx < 0) {
          beginx = 0;
        }
      }

      //用canvas绘制图片
      const ctx = wx.createCanvasContext('myCanvas');
      ctx.stroke();
      ctx.drawImage(imgSrc, beginx, beginy, w, h);
      ctx.globalCompositeOperation = "destination-over";
      ctx.setLineWidth(4);
      ctx.setStrokeStyle('red');
      ctx.strokeRect(theBeginx+2, theBeginy+2, theWidth-5, theHeight-5);
      ctx.draw();
      arr = [theBeginx + 2 - beginx, theBeginy + 2 - beginy, theBeginx + theWidth - 3 - beginx, theBeginy + theHeight - 3 - beginy];
      console.log(arr);
      
    }
  })
  setTimeout(function () {
    console.log(arr);
    return arr;
  }, 100);
  
}

封装的函数中出现了异步问题,所以加了定时器,已下是打印数据

clipboard.png
第一行是第一串代码打印的值undefined
第二行和第三行是函数中的打印值
现在就是想知道怎么解决那个赋值是undefined的问题

阅读 3.9k
3 个回答

在外部声明即可,将赋值方法部分放在请求的成功回调里就可以了。

你都说了是异步问题了,直接赋值肯定会有问题啊,所有依赖于请求的操作都要放在异步回调里。

使用async await

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题