Home > other >  How can I make this Node.js code more concise?
How can I make this Node.js code more concise?

Time:10-30

I need to make three network requests within one function and I have wrapped these three network requests into an asynchronous function that uses await-to-js to receive errors or responses. Is there any way to make this three ifs into one, but return an error message as soon as one of them has an error?

        let [loginErr,loginRes] = await to(sa_login(req))
        if(loginErr){
            return ctx.sendError('400',loginErr)
        }
        let [infoErr,infoRes] = await to(sa_getUserInfo(loginRes))
        if(infoErr){
            return ctx.sendError('400',infoErr)
        }
        let [courseInfoErr,courseInfoRes] = await to(sa_getCourseInfo(loginRes))
        if (courseInfoErr){
            return ctx.sendError('400',courseInfoErr)
        }

CodePudding user response:

You'll want to drop that await-to-js that transforms promise rejections into error/result tuples here and just use the plain functions.

Once you've done that, you can just

try {
  const loginRes = await sa_login(req);
  const infoRes = await sa_getUserInfo(loginRes);
  const courseInfoRes = await sa_getCourseInfo(loginRes);
} catch (err) {
  return ctx.sendError("400", err);
}

CodePudding user response:

A possible solution could be:

try {
 const[loginErr,loginRes] = await to(sa_login(req));
 if(loginErr) throw loginErr;
 const [infoErr,infoRes] = await to(sa_getUserInfo(loginRes))
 if(infoErr) throw infoErr;
 const [courseInfoErr,courseInfoRes] = await to(sa_getCourseInfo(loginRes))if 
 if (courseInfoErr) throw courseInfoErr;
} catch(e) { return ctx.sendError('400', e); }

This is not the best solution and however you should re-throw your error in the catch statement and catch it on the top level, when you call this function. I don't have the entire code to understand what you're doing, but i guess this will work for you

  • Related