Home > Back-end >  await IIFE result vs separate async function
await IIFE result vs separate async function

Time:12-17

I have been refactoring some legacy code and found the following example:

    // inside other function
    const isTriggerValid = await (async () => {
        try {
            const triggers = await db.any(getTriggerBeforeBook, { paramId });
            if (!triggers || triggers.length === 0) {
                return false;
            }

            return true;
        } catch (e) {
            logger.error(e);
            return false;
        }
    })();

and I'd like to ask, what is the point between it, and the code below?

   const isTriggerValid = async (paramId) => {
     try {
        const triggers = await db.any(getTriggerBeforeBook, { paramId });
          if (!triggers || triggers.length === 0) {
              return false;
          }
        return true;
     } catch {
        return true;
     }
   }

And then invoking it with const trigger = await isTriggerValid(paramId) ?

I know absolutely for sure that this keyword hasn't been used in it.

CodePudding user response:

The main difference would be that in the old version isTriggerValid would be the functions result and in the new one it's a function and the result would be called trigger. Other than that both are invoking the same function.

Regarding your concern about this. In both variants it's an arrow-function inheriting the parent-context so even if it was used it would be the same in both.

  • Related