Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
I want to know how I can wait for a return function to send data before executing the next line of code

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();
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda