简体   繁体   English

使用async / await是从Promise.reject()接收已解决的Promise的唯一方法吗?

[英]Is using async/await the only way to receive a resolved promise from Promise.reject()?

I have the following code below. 我下面有以下代码。 What i want to do is handle the network error case and the returned HTTP server error cases separately. 我想做的是分别处理网络错误情况和返回的HTTP服务器错误情况。

fetch("$imageUploadUrl", {
          method: "POST",
          mode: "same-origin",
          cache: "no-store",
          credentials: "same-origin",
          redirect: "error",
          referrer: "origin",
          body: formData
      }).catch(function(error) {
        failure("There was an error while uploading the image");
      }).then(function(response) {
          if (response.ok){
            return Promise.resolve(response.json());
        } else {
            return Promise.reject(response.text())
        }
      }).then(function(result) {
        success(result.location);
      }).catch(function(errorText) {
          return failure (errorText);
      })

However, unlike Promise.resolve() , Promise.reject() does not wait to resolve the promise from response.text() before returning it. 但是,与Promise.resolve()不同, Promise.reject() response.text()在返回前不等待从response.text()解析承诺。 I have managed to receive a resolved promise by adding async/await like that: 我设法通过添加async / await来收到已解决的诺言:

fetch("$imageUploadUrl", {
          method: "POST",
          mode: "same-origin",
          cache: "no-store",
          credentials: "same-origin",
          redirect: "error",
          referrer: "origin",
          body: formData
      }).catch(function(error) {
        failure("There was an error while uploading the image");
      }).then(async function(response) {
          if (response.ok){
            return Promise.resolve(response.json());
        } else {
            return Promise.reject(await response.text())
        }
      }).then(function(result) {
        success(result.location);
      }).catch(function(errorText) {
          failure(errorText);
      });

Is this the only way to reach my goal? 这是达到我目标的唯一方法吗?

I have also tried doing this: 我也尝试这样做:

fetch("$imageUploadUrl", {
          method: "POST",
          mode: "same-origin",
          cache: "no-store",
          credentials: "same-origin",
          redirect: "error",
          referrer: "origin",
          body: formData
      }).catch(function(error) {
        failure("There was an error while uploading the image");
      }).then(function(response) {
          if (response.ok){
            return Promise.resolve(response.json());
        } else {
            return Promise.reject(response.text())
        }
      }).then(function(result) {
        success(result.location);
      }).catch(function(textPromise) {
          return textPromise;
      }).then(function(text) {
        console.log(text);
      })

But the final then with the console.log is called always, even when i call Promise.resolve() in the code above it, as it was attached on the promise from fetch function itself. 但是,即使我在上面的代码中调用Promise.resolve()时,也总是调用console.log的最后一个,因为它附加在fetch函数本身的promise上。 Do you know why this happens. 你知道为什么会这样吗?

您可以等待诺言,然后拒绝它:

return response.text().then(text => Promise.reject(text));

And what about this version: 那这个版本呢:

const options = {
  method: 'POST',
  mode: 'same-origin',
  cache: 'no-store',
  credentials: 'same-origin',
  referrer: 'origin',
  body: formData
}

async function parseResponse (response) {
  try {
    success(await response.json())
  } catch () {
    failure(await response.text())
  }
}

function parseError (err) {
  failure(`Error uploading file: ${err}`)
}

fetch('$imageUploadUrl', options)
  .then(parseResponse)
  .catch(parseError)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM