如何在保留数据的同时链接 Promises?
How to chain Promises while keeping the data?
我有两个 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 并且效果很好,但我想尽可能避免这种反模式。
你可以 ,但在这种情况下,我显然会选择异步/等待:
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);
}
})();
我有两个 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 并且效果很好,但我想尽可能避免这种反模式。
你可以
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);
}
})();