Skip to content Skip to sidebar Skip to footer

Can Await And Then Be Mixed In One Implementation?

I'm wondering if await and .then can be used in the same async function? Here is my function: uploadImageToImgur: async function (file) { return new Promise(function(resolve, reje

Solution 1:

Yes, you can use mix await and then syntax - they both work on promises - but you shouldn't do so in the same function.

But that's not the main issue in your code. The problem is the use of the Promise constructor antipattern in the uploadImageToImgur function. Do not use async functions as callbacks. Do not create promises in then callbacks without returning them - rejections of response.json() are not caught by your code.

Yes, you will need the Promise constructor to promisify the reader, but that's it. Factor it out inside its own function so that you don't lead yourself into temptation. That if (file) condition inside the executor led to your promise being never resolved in some cases!

Cleaned up:

functionreadDataUrl(file) {
  returnnewPromise((resolve, reject) => {
    const reader = newFileReader();
    reader.onload = function() {
      resolve(this.result);
    };
    reader.onerror = reader.onabort = reject; // don't forget this!
    reader.readAsDataURL(file);
  });
}

uploadImageToImgur: asyncfunction(file) {
  const url = 'https://api.imgur.com/3/image',
  if (file) {
    const result = awaitreadDataUrl(file);
    const response = awaitfetch(url, {
      method: 'POST',
      headers: {
        "Authorization": 'my auth',
      },
      body: result.replace(/^data:image\/(png|jpg|jpeg|gif);base64,/, "")
    });
    const data = await response.json();
    return data.data.link;
  }
}

Post a Comment for "Can Await And Then Be Mixed In One Implementation?"