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

350
Visualizações
How do I resolve a promise in Node.js?

I am trying to make a simple weather application based on Node.js, like this one. My problem is that every mechanism I see is based on promises, and I don't understand the concept.

So, the code I see everywhere is like:

yrno.getWeather(LOCATION).then((weather) => {
    weather.getFiveDaySummary().then((data) => console.log('five day summary', data)); 
    weather.getForecastForTime(new Date()).then((data) => console.log('current weather', data));
    })
    .catch((e) => {
        console.log('an error occurred!', e);
    });

However, I was unable to find a way to resolve these promises and save the five day summary to a variable for later use.

How do I proceed?

Thanks, Robin

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Assign the Promise returned from yrno.getWeather(LOCATION) call to a variable.

Use Promise.all() to return results from both weather.getFiveDaySummary() and weather.getForecastForTime(new Date()) calls.

Chain .then() to the result of call to get the data at initial and subsequent .then() chained to variable identifier which returned initial Promise values.

let weatherData = yrno.getWeather(LOCATION).then(weather => {
  // note `return`, alternatively omit `return` and `{`, `}` at arrow function
  // .then(weather => Promise.all(/* parameters */))
  return Promise.all([weather.getFiveDaySummary()
                    , weather.getForecastForTime(new Date())]);
});

weatherData
// `results` is array of `Promise` values returned from `.then()`
// chained to `yrno.getWeather(LOCATION).then((weather)`
.then(results => {
  let [fiveDaySummary, forecastForTime] = results; 
  console.log('five day summary:', fiveDaySummary
             , 'current weather:', forecastForTime); 
  // note `return` statement, here
  return results
})
.catch(e => {
  // `throw` `e` here if requirement is to chain rejected `Promise`
  // else, error is handled here
  console.log('an error occurred!', e);
});

// weatherData
// .then(results => { // do stuff with `results` from first `weatherData` call })
// .catch(e => console.log(e));
over 4 years ago · Santiago Trujillo Relatório

0

An alternative to using promises directly is to use await/async.

// weather.js  
const yrno = require('yr.no-forecast')({
  version: '1.9', // this is the default if not provided,
  request: {
    // make calls to locationforecast timeout after 15 seconds
    timeout: 15000
  }
});

const LOCATION = {
  // This is Dublin, Ireland
  lat: 53.3478,
  lon: 6.2597
};

async function getWeather() {

  let weather = await yrno.getWeather(LOCATION);
  let fiveDaySummary = await weather.getFiveDaySummary();
  let forecastForTime = await weather.getForecastForTime(new Date());

  return {
    fiveDaySummary: fiveDaySummary,
    forecastForTime: forecastForTime,
  }
}

async function main() {
  let report;

  try {
    report = await getWeather();
  } catch (e) {
    console.log('an error occurred!', e);
  }

  // do something else... 
  if (report != undefined) {
    console.log(report); // fiveDaySummary and forecastForTime
  }
}

main(); // run it

you can run this (node.js 7) with:

node --harmony-async-await weather

You can use await/async on older targets by using Babel or Typescript to transpile it down for you.

Bonus (based off your comments) - I wouldn't do it this way, but just to show you it can be done:

const http = require('http');

const port = 8080;

http.createServer(
  async function (req, res) {
    let report = await getWeather(); // see above
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("" + JSON.stringify(report.fiveDaySummary));
    res.end('Hello World\n');
  })
  .listen(port);

enter image description here

again with node --harmony-async-await weather or transpile it.

over 4 years ago · Santiago Trujillo 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