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

214
Visualizações
NodeJs javascript: wait until the previous object property is assigned before assigning the next property

Suppose I have code like this:

let result = {
  name: downloadNameFromInternetVerySlow(),
  isFamous: determineIfNameIsFamous(this.name);
}
const downloadNameFromInternetVerySlow = () => {
    path = "/home";
    const folders = fs.readdirSync(path).filter(file => fs.lstatSync(path).isDirectory());
    console.log(folders);
    return folders[0];
}

downloadNameFromInternetVerySlow can take a long time, meanwhile determineIfNameIsFamous depends on downloadNameFromInternetVerySlow's result to return correct value.

How do I make sure determineIfNameIsFamous only runs after downloadNameFromInternetVerySlow is done?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can convert downloadNameFromInternetVerySlow to a Promise(if not already). and then user await to wait till it finished. Otherwise you can use Promise.then()

(This should be inside an async function)

let name =  await downloadNameFromInternetVerySlow(),
let isFamous = determineIfNameIsFamous(this.name);

let result = {
  name,
  isFamous
}

Another method using Promise.then

let name, isFamous;
downloadNameFromInternetVerySlow().then(result => {
    name = result;
    isFamous = determineIfNameIsFamous(this.name);
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Assuming downloadNameFromInternetVerySlow is asynchrononous (otherwise it would already work like you want), the solution is to use await.

Please note, to be able to do that, this code needs to be wrapped in an async function (or or top level with top level await available.)

async function getAndUseResult(){
  let result = {
    name: await downloadNameFromInternetVerySlow(),
    isFamous: determineIfNameIsFamous(this.name)
  }
  console.log(JSON.stringify(result))
}
getAndUseResult();
about 4 years ago · Juan Pablo Isaza Relatório

0

Async/await

There’s a special syntax to work with promises in a more comfortable fashion, called “async/await”.

An async function returns a promise, like in this example:

const doSomethingAsync = () => {
  return new Promise(resolve => {
    setTimeout(() => resolve('I did something'), 3000)
  })
}

When you want to call this function you prepend await, and the calling code will stop until the promise is resolved or rejected. One caveat: the client function must be defined as async. Here's an example :

const doSomething = async () => {
  console.log(await doSomethingAsync())
}
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