如何在保存数据的同时链接Promises?

时间:2019-08-26 20:55:12

标签: javascript node.js promise es6-promise

我有两个这样链接的API调用:

let weatherPromise;

if (crds) {
    weatherPromise = mapbox.getLocation(crds)
    .then(locData => darksky.getWeather(crds))
    .then(weatherData => Object.assign(weatherData, {city: locData.city}));
} else if (term) {
    weatherPromise = mapbox.getCoords(term)
    .then(locData => darksky.getWeather(locData.crds));
} else {
    weatherPromise = Promise.reject({error: 'Aborted due to unexpected POST-Body'});
}

weatherPromise.then(weatherData => {
    io.emit('update', weatherData);
    console.log(`Answer sent: ${JSON.stringify(weatherData)}`);
}, reject => {
    io.emit('update', reject);
    console.error(reject.error);
});

但是它根本不起作用。错误处理无处不在(主要是记录undefined并失败),例如locData在第二then()中似乎不再可用。我尝试嵌套Promises,但效果很好,但如果可以的话,我想避免使用这种反模式。

1 个答案:

答案 0 :(得分:2)

您可以nest `.thens´,但是在这种情况下,我显然会使用async / await:

async function retrieveWeather() {
   if (crds) {
      const locData = await mapbox.getLocation(crds);
      const weatherData = await darksky.getWeather(crds);

      return Object.assign(weatherData, {city: locData.city});
   } else if (term) {
     const locData = await mapbox.getCoords(term);
     const weatherData = await darksky.getWeather(locData.crds);

     return weatherData;
   } else {
     throw {error: 'Aborted due to unexpected POST-Body'};
   }
}

(async function sendWeather() {
  try {
    const weatherData = await retrieveWeather();
    io.emit('update', weatherData);
    console.log(`Answer sent: ${JSON.stringify(weatherData)}`);
  } catch(error) {
     io.emit('update', error);
     console.error(reject.error);
  }
})();