Javascript 如何解析Node.js中的承诺?
我正在尝试基于Node.js制作一个简单的天气应用程序,比如。我的问题是,我看到的每一种机制都是基于承诺的,我不理解这个概念 因此,我在任何地方看到的代码都是这样的:Javascript 如何解析Node.js中的承诺?,javascript,node.js,promise,Javascript,Node.js,Promise,我正在尝试基于Node.js制作一个简单的天气应用程序,比如。我的问题是,我看到的每一种机制都是基于承诺的,我不理解这个概念 因此,我在任何地方看到的代码都是这样的: yrno.getWeather(LOCATION).then((weather) => { weather.getFiveDaySummary().then((data) => console.log('five day summary', data)); weather.getForecastFor
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);
});
然而,我无法找到一种方法来解决这些承诺,并将五天总结保存到一个变量中供以后使用
我该如何进行
谢谢,
Robin将从
yrno.getWeather(LOCATION)
调用返回的Promise
分配给变量
使用Promise.all()
将.then()
链接到调用的结果,以获取初始和后续的数据。然后()
链接到返回初始Promise
值的变量标识符
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));
直接使用承诺的替代方法是使用wait/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
您可以通过以下方式运行此(node.js 7):
节点——和谐异步等待天气
通过使用Babel或Typescript为您向下传输,您可以在较旧的目标上使用wait/async
奖金(根据您的评论)-我不会这样做,但只是为了向您表明这是可以做到的:
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);
再次使用节点--harmony async等待天气
或传输天气 你应该查一下闭包。data
最后.then()
函数是否包含您试图存储的数据?您不保存摘要,而是保存承诺。当您想使用它时,请使用然后
方法等待它,并将值作为参数传递。我想您可以从可能的重复开始,您甚至不需要--harmony
,因为7.6.Wow,。我需要试试这个,因为它太棒了。这不是我的首选答案,我还没有测试过,但我期待着尝试!非常感谢你!如果正确缩进代码,它看起来就不会像是在return
语句之后有代码。