承诺不完成拒绝

发布于 2025-01-19 06:07:54 字数 2638 浏览 4 评论 0原文

因此,我的表格具有以下功能:

const formSubmit = async (formData) => {
  const response = await SubmissionsResource.create(formData)
  const { data, status } = response
  console.log('Request completed.')
  if (status === 201) {
    toast.success('Submission created.')
  } else {
    toast.error('Something went wrong.')
    console.error(data)
  }
}

使用以下功能:使用以下

const SubmissionsResource = {
  create: ({ formData }) => (
    Request.privatePost(apiUrl('submissions'), formData)
  ),
}

内容:

export const Request = {
  privateRequest: ({ data, method, params, url }) => {
    axios.interceptors.request.use((request) => {
      request.headers.authorization = getBearerToken()
      return request
    }, (error) => Promise.reject(error))

    axios.interceptors.response.use(
      (response) => response,
      async (error) => {
        const originalRequest = error.config

        // If request is coming from a sign in attempt
        if (error.response.status === 401 && originalRequest.url.includes('auth/token')) {
          return Promise.reject(error)
        }

        // If request is coming from elsewhere, assume token might be expired
        if (error.response.status === 401 && !originalRequest._retry) {
          originalRequest._retry = true
          const refresh_token = LocalStorageService.getRefreshToken()
          const response = await axios.post(
            `${API_BASE}/oauth/token`,
            { client_id, client_secret, grant_type: 'refresh_token', refresh_token }
          )
          if (response.status === 200) {
            LocalStorageService.setUser(response.data)
            axios.defaults.headers.common.Authorization = getBearerToken()
            return axios(originalRequest)
          }
          return Promise.reject(error)
        }
        return Promise.reject(error)
      }
    )
    return axios({ method, url, data, params })
  },
  privatePost: (url, data) => (
    Request.privateRequest({ method: 'post', data, url })
  )
}

当响应成功时,我总是会看到“请求已完成”日志,并且我看到toast.success 消息。但是,当请求失败时,我从未看到“请求已完成”日志,也没有看到toast.error消息。

如果响应未经授权(401个状态代码),它成功地做到了,并且在所有其他情况下,都应拒绝承诺并返回错误,则Axios Interceptor应重试(401状态代码)。

request.privaterequest应拒绝承诺,然后将错误返回request.privatepost,该错误应返回到submissionsresource.create,然后最后返回到form ubmit。但是,它没有完成承诺并返回错误,而只是停止了整个函数,并且永远不会进入“请求已完成”日志。

我假设这是由于对我的承诺有不正确的理解,但我无法弄清楚那是什么。为什么未完成承诺并继续进入form ubmit中的下一行?

So I have a form that submits with the following function:

const formSubmit = async (formData) => {
  const response = await SubmissionsResource.create(formData)
  const { data, status } = response
  console.log('Request completed.')
  if (status === 201) {
    toast.success('Submission created.')
  } else {
    toast.error('Something went wrong.')
    console.error(data)
  }
}

Which uses the following:

const SubmissionsResource = {
  create: ({ formData }) => (
    Request.privatePost(apiUrl('submissions'), formData)
  ),
}

Which uses the following:

export const Request = {
  privateRequest: ({ data, method, params, url }) => {
    axios.interceptors.request.use((request) => {
      request.headers.authorization = getBearerToken()
      return request
    }, (error) => Promise.reject(error))

    axios.interceptors.response.use(
      (response) => response,
      async (error) => {
        const originalRequest = error.config

        // If request is coming from a sign in attempt
        if (error.response.status === 401 && originalRequest.url.includes('auth/token')) {
          return Promise.reject(error)
        }

        // If request is coming from elsewhere, assume token might be expired
        if (error.response.status === 401 && !originalRequest._retry) {
          originalRequest._retry = true
          const refresh_token = LocalStorageService.getRefreshToken()
          const response = await axios.post(
            `${API_BASE}/oauth/token`,
            { client_id, client_secret, grant_type: 'refresh_token', refresh_token }
          )
          if (response.status === 200) {
            LocalStorageService.setUser(response.data)
            axios.defaults.headers.common.Authorization = getBearerToken()
            return axios(originalRequest)
          }
          return Promise.reject(error)
        }
        return Promise.reject(error)
      }
    )
    return axios({ method, url, data, params })
  },
  privatePost: (url, data) => (
    Request.privateRequest({ method: 'post', data, url })
  )
}

When the response is successful, I always see the "Request completed" log, and I see the toast.success message. However, when the request fails, I never see the "Request completed" log, nor the toast.error message.

The axios interceptor should retry once if the response comes back unauthorized (401 status code), which it successfully does, and in all other cases, reject the promise and return the error.

Request.privateRequest should reject the promise and return the error to Request.privatePost, which should return back to SubmissionsResource.create, and then finally to formSubmit. However, instead of completing the promise and returning an error, it just halts the entire function and doesn't ever get to the "Request completed" log.

I'm assuming this is due to an incorrect understanding with promises on my end, but I can't figure out what that is. Why isn't the promise being completed and continuing on to the next line within formSubmit?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有你我更好 2025-01-26 06:07:54

通过返回Promise.Reptect(),您是告诉Axios拒绝网络请求返回的承诺,但呼叫代码不会引起任何拒绝。

尝试尝试:

const formSubmit = async (formData) => {
  try {
    const response = await SubmissionsResource.create(formData)
    const { data, status } = response
    console.log('Request completed.');
    toast.success('Submission created.')
  } catch(error) {
    if (error.response.status === 401)
      toast.error('Bad news: 401.');
    else 
      toast.error('Some other kind of bad news.');
  }
}

By returning Promise.reject(), you're telling axios to reject the promise returned by the network request, but the calling code doesn't catch any rejection.

Try try-ing:

const formSubmit = async (formData) => {
  try {
    const response = await SubmissionsResource.create(formData)
    const { data, status } = response
    console.log('Request completed.');
    toast.success('Submission created.')
  } catch(error) {
    if (error.response.status === 401)
      toast.error('Bad news: 401.');
    else 
      toast.error('Some other kind of bad news.');
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文