0

I have a function that returns and axios promise with the data that I need to work with. After getting the data from getUsersQA() function, I have a promise chain in order to promise the data and send the return message. The code works when I invoke the function using an event (Post Method). But when I setup this function with a scheduled cron on netlify serverless functions I am getting this output.

Feb 16, 02:55:01 AM: 2f35893d INFO   Fetching Users...
Feb 16, 02:55:01 AM: 2f35893d Duration: 94.40 ms    Memory Usage: 73 MB Init Duration: 370.93 ms    

Immediately upon invoking getUsersQA() the function is returning for some reason when it is invoked with an event the code works.

export async function handler(event: APIGatewayEvent, context: Context) {
  // Fetching Slack Users
  const users = await getSpaceUsers(client);

  // Fetching QA Data & Pushing Slack Message
  const period = computePeriods();
  let blocksContent: any[] = [];

  const qaData = await getUsersQA(period.lastMonth);
  for (const puser of qaData) {
    // FIREBASE LOGIC

    if (puser.avg_score < 85) {
      const block = userQAInfo(puser, users?.get(puser.email));
      blocksContent.push(block);
    }
  }

  try {
    // Call the chat.postMessage method using the WebClient
    const result = await client.chat.postMessage({
      channel: "",
      text: ``,
      blocks: blocksContent,
    });
    console.log(result);
    return {
      statusCode: 200,
    };
  } catch (error) {
    console.error(error);
    return {
      statusCode: 200,
    };
  }
}

module.exports.handler = schedule("*/5 * * * *", handler);

This is my getUSersQA asyn function.

export async function getUsersQA(period: string[]): Promise<playvoxUser[]> {
  return axios({})
    .then((response) => {
      let playvoxStats: playvoxUser[];
      playvoxStats = response.data.result;
      formatPlayvoxResponse(playvoxStats);
      let lowQAStats: playvoxUser[] = [];
      playvoxStats.forEach((user) => {
        user.avg_score =
          Math.round((user.avg_score + Number.EPSILON) * 100) / 100;
        lowQAStats.push(user);
      });
      return lowQAStats;
    })
    .catch((err) => {
      console.log("ERROR while fetching USERS");
      return err;
    });
}
Charles Semaan
  • 304
  • 2
  • 13
  • 1
    Well you neither `return` nor `await` the chained promises of `getUsersQA`, so why would the `handler` wait for it? – Bergi Feb 16 '22 at 02:24
  • Btw, why are you even chaining promises using `.then()`, instead of using `await`? Also you [cannot use `forEach`](https://stackoverflow.com/a/37576787/1048572) like that - though your callback isn't even asynchronous? – Bergi Feb 16 '22 at 02:25
  • @Bergi I fixed my code. Removed chaining and used await instead. I also remove foreach and used regular for loop. Now I am getting a timeout issue in netlify, altough in development when i trigger my function using https://url/.netlify/functions/MainNotifications the code works flawlessly and is executed within less 10secons which is the timeout. What am i doing wrong? – Charles Semaan Feb 16 '22 at 17:12
  • Also unless `schedule` returns a function, it won't do anything. You can't schedule lambas like that – Evert Feb 16 '22 at 17:12
  • @Evert Should I wrap my code in a function and return it in the handler? I don't understand. If you can provide me with a reference to check that would be great. Scheduled functions are recently launched and the documentation here https://github.com/netlify/labs/blob/main/features/scheduled-functions/documentation/README.md is pretty limited. – Charles Semaan Feb 16 '22 at 17:18
  • Are `userQAInfo` or `users?.get` asynchronous? – Bergi Feb 16 '22 at 17:50
  • No. `UsersQAInfo` manipulates data given and returns an object. It is not fetching from anywhere. `users?.get` , users here is a map and i am getting a item with a certain key. – Charles Semaan Feb 16 '22 at 18:42
  • @charleslenx maybe it's not a real lambda then but some netlify flavour. What you export in a lambda must be a function, and generally you would use somelike 'cloudwatch events' to schedule them. – Evert Feb 16 '22 at 18:45
  • @charleslenx Ah ok, I guess then even the original `forEach` should have worked, only its callback shouldn't have been an `async` function – Bergi Feb 16 '22 at 21:54
  • Yeah the forEach was working in development when it's fired via an event. My code is not working only in production when it's invoked via cron jobs. – Charles Semaan Feb 16 '22 at 22:36

0 Answers0