简体   繁体   English

如何正确处理 Promise 中的拒绝

[英]How to properly handle reject in Promises

We have this function in our code that is used to log in a user我们的代码中有这个 function 用于登录用户

const userLogin = loginData => {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await auth.post("/login", loginData);
      resolve(res);
    } catch (error) {
      reject(error);
    }
  });
};
// Calling function
const loginSubmit = async values => {
  try {
    const res = await userLogin(values);
    console.info(res);
  } catch (error) {
    console.error("Catch: ", error);
  }
};

But from this stackoverflow answer , try-catch blocks are redundant in Promises.但是从这个 stackoverflow 答案来看, try-catch块在 Promise 中是多余的。 I wanted to try and clean this code, so I changed the code above into:我想尝试清理这段代码,所以我将上面的代码更改为:

const userLogin = loginData => {
  return new Promise(async (resolve, reject) => {
    const res = await auth.post("/login", loginData);
    if (res.status !== 201) {
      reject(new Error("Error"));
    }
    resolve(res);
  });
};

However, when I tried to login with incorrect credentials, the console logs an Uncaught (in promise) Error: Request failed with status code 400但是,当我尝试使用不正确的凭据登录时,控制台会记录一个Uncaught (in promise) Error: Request failed with status code 400

I'm not really familiar with creating my own promises, so I don't know how to do this properly.我不太熟悉创建自己的承诺,所以我不知道如何正确地做到这一点。

Couple of problems in your code:您的代码中有几个问题:

  • You are unnecessarily creating a promise;您不必要地创建了 promise; auth.post(..) already returns a promise, so you don't need to create a promise yourself and wrap auth.post(...) inside a promise constructor. auth.post(..)已经返回了 promise,因此您不需要自己创建 promise 并将auth.post(...)包装在 promise 构造函数中。

  • Another problem in your code is that executor function (function passed to the promise constructor) is marked as async ;代码中的另一个问题是执行程序 function (传递给 promise 构造函数的函数)被标记为async it should not be an async function .不应该是异步 function

Your function could be re-written as:您的 function 可以重写为:

const userLogin = async (loginData) => {
    const res = await auth.post("/login", loginData);
    
    if (res.status !== 201) {
      throw new Error("Error"));
    }

    return res;
};

You could also re-write your function as:您还可以将 function 重写为:

const userLogin = async (loginData) => {
    return auth.post("/login", loginData);       
};

Don't forget to use the catch in the code that calls this function.不要忘记在调用此 function 的代码中使用catch

You might want to read the following article to understand whether you need the try-catch block:await vs return vs return await您可能想阅读以下文章以了解您是否需要try-catch块:await vs return vs return await

I think that in your case since you call to async function inside the constructor of the promise you need to use try catch.我认为,在您的情况下,由于您在 promise 的构造函数中调用异步 function ,因此您需要使用 try catch。
The answer you referred is correct as long as the error happened while you are in the constructor (ie the Promise object is in the making), however in your case the rejection of the auth function happens long after the Promise was constructed and therefore it is not rejecting it. The answer you referred is correct as long as the error happened while you are in the constructor (ie the Promise object is in the making), however in your case the rejection of the auth function happens long after the Promise was constructed and therefore it is不拒绝它。

BTW - You don't have to await in the promise.顺便说一句 - 您不必在 promise 中await You may do the following:您可以执行以下操作:

const userLogin = loginData => {
  return new Promise(async (resolve, reject) => {
    const prom = auth.post("/login", loginData)
      .then((res) => {
        if (res.status !== 201) {
          reject(new Error("Error"));
        }
        resolve(res);
      });
    resolve(prom);
  });
};

Since you resolve the async auth call, any rejection by the auth call will be reflect as a rejection from you function由于您resolve了异步auth调用,因此auth调用的任何拒绝都将反映为您的拒绝 function

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

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