0

I am having a bit of a problem with my code(Node.js). I want have 2 files app.js and state.js, i basically created the two to try and solve the issue i am having.

on the second file "State.js" i have a function that returns an object and i delayed the return by 10 secs (With impression of a slow internet, etc). and i am trying to retrieve the object in the app.js file. but at the moment, it doesn't work. I have tried using promise (async & await) but that returns an error on the terminal, i also tried running a setInterval to monitor the variable i which to use in retrieving the object to only execute when it has data but that doesn't work as well. Please I need assistance as soon as possible.

Below is the code examples for the 2 scenario.

=========================== state.js file =======================

function test(val){
    setTimeout(() => {
        return {
            code: 0,
            value: val
        }
    }, 10000);
}

module.exports = test;

========================== app.js file (Using the promise approach)============================

async function runNow(){
    let v = await t('some string');
    console.log(v.value)
}

runNow();

================================== app.js (using the interval approach) ==========

function runNow(){
    let engine = setInterval(() => {
        let v = t('some string');
        if(v === null || v === undefined){
            console.log(v);
        }else{
            clearInterval(engine);
            console.log(v.value);
        }
    }, 5000);
    // console.log(v.value);
}

runNow();
Octagod
  • 90
  • 1
  • 1
  • 12
  • returning a value in setTimeout is pointless, the value goes nowhere - `the promise approach` requires that you have a Promise to await - you don't – Bravo Sep 21 '21 at 23:55
  • @bravo what do you suggest i do? and how do i create a promise – Octagod Sep 22 '21 at 00:05
  • see: [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) – pilchard Sep 22 '21 at 00:07

2 Answers2

1

You have to use promise or callback to accomplish what you're wanting to do here.

If I return something from the callback fucntion of setTimeout(callback, time) it actually doesn't get returned by the setTimeout funciton.

The implementation of setTimeout is probably similar to something like this.

function setTimeout(callback, time, ...args) {
    // After the given time it executes the callback
    callback(...args);
}

The desired implementation of your state.js file would be like the following:

function testWithPromise(val) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        code: 0,
        value: val,
      });
    }, 5000);
  });
}

function testWithCallback(val, callback) {
  setTimeout(() => {
    callback({
      code: 0,
      value: val,
    });
  }, 3000);
}

// export the function


// use it in other modules as
testWithCallback("callback_approach", console.log);
testWithPromise("promise_approach").then(console.log);

// or with an async function
async function getValue() {
  const value = await testWithPromise("async_promise");
  console.log(value);
}

//getValue();
h-sifat
  • 1,455
  • 3
  • 19
1

You need to create a promise in order for await to wait for it

Try:

function test(val) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({code: 0, value: val});
    }, 10000);
  });
}

async function runNow() {
  let v = await test('someString');
  console.log(v.value);
}
Leshawn Rice
  • 617
  • 4
  • 13