简体   繁体   中英

async and await call an api for a response,

I have a function that looks like this,

const addItem = async(req, res, next) => {
    const itemApi = new Connector({
        url: '/item',
        method: 'POST',
        headers: {},
        body: {item: "item name"}
    });
    try {
       const response = await itemApi.call();
       if(response.data && response.data.errors) {
           return response.data.errors;
       } else {
         return response.data;
       }
   } catch(error) {
      console.log(error);
   }

I invoking this method like this,

addItem(req, res, next)
   .then((response) => console.log(response))
   .catch((error) => console.log(error))

It seems that the then is always called and catch never called even if the api returns an error? Am I doing something wrong?

You are using a try/catch bloc k but not throwing back the error from catch block and hence the .catch of the function call is not executed since no unhandled error is present in the async function

You can throw and error and it would work as you expect it to

const addItem = async(req, res, next) => {
    const itemApi = new Connector({
        url: '/item',
        method: 'POST',
        headers: {},
        body: {item: "item name"}
    });
    try {
       const response = await itemApi.call();
       if(response.data && response.data.errors) {
           return response.data.errors;
       } else {
         return response.data;
       }
   } catch(error) {
      console.log(error);
      throw new Error(error);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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