1

I have 2 files in JavaScript (node). In the first file I have a function which is then exported inside of a setInterval() call because I want it to be self invoking every minute. The issue is when I try to export default my setInterval(method, 60000) and then import it into another file and console.log() I am getting the return value of the interval method itself rather than the value I want returned.

1st JS File


  const makeApiCall = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/posts');

  const results = await res.json();

  return results;
};

export default setInterval(makeApiCall, 60000);

JS File 2

import makeIntervalCall from './file1.js';

console.log({ rezults: makeIntervalCall });

console log output

{                                                                                                                                                                      
  rezults: Timeout {
    _idleTimeout: 2000,
    _idlePrev: [TimersList],
    _idleNext: [TimersList],
    _idleStart: 2485,
    _onTimeout: [AsyncFunction: makeApiCall],
    _timerArgs: undefined,
    _repeat: 2000,
    _destroyed: false,
    [Symbol(refed)]: true,
    [Symbol(kHasPrimitive)]: false,
    [Symbol(asyncId)]: 43,
    [Symbol(triggerId)]: 0
  }
}

So when using the interval called function in another file it logs out the Timeout rather than the results. How do I extract the actual api results from this when importing into another file?

CodeConnoisseur
  • 1,452
  • 4
  • 21
  • 49
  • The interval calls the function multiple times; there is no single return value that you could export. – Bergi Oct 07 '22 at 02:27
  • @CodeConnoisseur my apologies, I misunderstood your question initially – Phil Oct 07 '22 at 02:33

1 Answers1

1

Export a function that accepts a listener function which you can pass to makeApiCall.

It's also common in these scenarios to provide a remove or unsubscribe function to assist cleanup.

const makeApiCall = async (listener) => {
  const res = await fetch("https://jsonplaceholder.typicode.com/posts");
  if (!res.ok) {
    throw new Error(`${res.status}: ${res.statusText}`);
  }
  listener(await res.json());
};

export default (listener) => {
  const timer = setInterval(makeApiCall, 60000, listener);
  return () => {
    clearInterval(timer);
  };
};

And use it like this

import makeIntervalCall from "./file1.js";

const unsub = makeIntervalCall((results) => {
  console.log(results);
});

// and when you want the interval to stop
unsub();
Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thanks, Phil! How would I store the value of the results in a variable that is available outside of the `makeIntervalCall` scope in the file2.js – CodeConnoisseur Oct 07 '22 at 02:36
  • @CodeConnoisseur why would you need one? You could always declare a variable anywhere you want and assign it a value inside the _listener_ function but you'd need to consider the timing of **when** that value is assigned – Phil Oct 07 '22 at 02:41
  • If I wanted to use the return value elsewhere in the file...maybe multiple places. If I do something like this I get undefined: let test; makeIntervalCall((results) => (test = results)); console.log(test); // undefined – CodeConnoisseur Oct 07 '22 at 02:44
  • but if I `console.log()` inside of the func invocation then I do see my results logged. But trying to access the results outside of that function scope then I can't see the results. – CodeConnoisseur Oct 07 '22 at 02:45
  • 1
    Exactly, it's all about timing. I would advise creating another function to pass the results to or just move any logic requiring the result into the _listener_. See also [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086/283366) – Phil Oct 07 '22 at 02:48
  • Appreciate your help, Phil! – CodeConnoisseur Oct 07 '22 at 02:50