Home > Blockchain >  I want to know how I can wait for a return function to send data before executing the next line of c
I want to know how I can wait for a return function to send data before executing the next line of c

Time:09-22

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();

CodePudding user response:

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();

CodePudding user response:

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);
}
  • Related