Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Invoke JavaScript Function with setInterval and return value using import and export in different files

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading