可以等待然后混入一个实现中吗?

时间:2019-02-07 13:40:36

标签: javascript asynchronous promise async-await

我想知道await和.then是否可以在同一异步函数中使用? 这是我的功能:

uploadImageToImgur: async function (file) {
return new Promise(function(resolve, reject) {
  const url = 'https://api.imgur.com/3/image',
  reader  = new FileReader();

  if (file) {
    reader.readAsDataURL(file);
  }

  reader.onloadend = async function () {
    let { result } = reader;

    try {
      const request = await fetch(url, {
        method: 'POST',
        headers: {
          "Authorization": 'my auth',
        },
        body: result.replace(/^data:image\/(png|jpg|jpeg|gif);base64,/, "")
      })
      .then((response) => {
        response.json()
        .then(data => {
          resolve(data.data.link)
        })
      });
    } catch (e) {
      reject(e);
    }
  }
});
},

然后,我在另一个函数中调用此函数,在该函数中,我使用从imgur API获得的链接将对象保存到indexedDb。

this.uploadImageToImgur(image)
  .then((image) => {
    let db = this.dbOpen.result,
        tx = db.transaction('EventsStore', 'readwrite'),
        store = tx.objectStore('EventsStore');

    event = store.put({ title, location, description, summary, date, time, image });
    //rest of the code
  });

我为什么选择这种方法?因为当我只使用await关键字(没有promise构造函数)时,在promise解决之前,数据已添加到数据库中; /不是我想要的(可能是我在某个地方犯了一个错误。idk)。

我的问题是上面的代码是否是实现此目的的正确方法(它按预期工作)还是应该对其进行重构?如果是这样,请告诉我如何。这个问题对我来说是有益的,而不是与特定问题有关。 谢谢。

1 个答案:

答案 0 :(得分:4)

是的,您可以混合使用awaitthen语法-它们都可以在promise上使用-但是you shouldn't do so in the same function

但这不是代码中的主要问题。问题是在uploadImageToImgur函数中使用Promise constructor antipattern。请勿将async function用作回调。在没有then的情况下,请勿在{{1​​}}回调中创建promise-您的代码不会捕获return的拒绝。

是的,您需要response.json()构造函数来promisify阅读器,仅此而已。将其分解为自己的功能,以免引起诱惑。执行者内部的Promise条件导致您的承诺在某些情况下永远无法解决!

已清理:

if (file)