如何使代码在以下async / await函数内等待?

时间:2017-08-24 09:51:50

标签: javascript asynchronous

我想在将图片上传到服务器之前调整图片大小(使用Firebase):

api.uploadPhoto = async (file = {}, field = {}) => {
  const canvas = document.getElementById('canvas')
  const img = document.createElement('img')
  const reader = new FileReader()
  let fileToUpload

  reader.onload = function (e) {
    img.src = e.target.result
    pica.resize(img, canvas).then(result => {
      fileToUpload = pica.toBlob(result, 'image/jpeg', 90))
    })
  }
  reader.readAsDataURL(file)

  // run the code below only when reader.onload has finished 

  return await imageUpload.toFirebase(fileToUpload, field)
}

问题是imageUpload.toFirebasereader.onload之前运行。如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

将上传内容移至回调...

api.uploadPhoto = async (file = {}, field = {}, callback) => {
  const canvas = document.getElementById('canvas');
  const img = document.createElement('img');
  const reader = new FileReader();
  let fileToUpload;

  reader.onload = function (e) {
    img.src = e.target.result;
    pica.resize(img, canvas).then(result => {
      fileToUpload = pica.toBlob(result, 'image/jpeg', 90));
    });

    reader.readAsDataURL(file);
    callback(await imageUpload.toFirebase(fileToUpload, field));

  }
};