node.js - 使用 Promise 获取 JSON 文件
问题描述
我是新的承诺,我有一些关于这些的问题。
我需要从一个 url 为我的 node.js 应用程序获取一个 JSON 文件(包含天气信息),所以我创建了一个getJSON()
使用 https 模块const https = require('https');
“返回”文件的函数:
function getJSON(url, resolve) {
https.get(url, function(res) {
let json = '';
res.on('data', function(chunk) { json += chunk; });
res.on('end', function() { resolve(JSON.parse(json)); });
}).on('error', function(err) { console.log(err); });
};
正如你所看到的,它实际上并没有返回值,但它解决了它,因为我用一个承诺调用函数:
function weather() {
let json = new Promise(function(res) {getJSON('https://api.openweathermap.org/data/2.5/weather?APPID=APIKEY&q=City&units=metric', res);})
json.then(function(weatherJSON) {
// and here i can use the file
});
}
所以这行得通,但我觉得它可能会更好,我可以优化它吗?我什至不应该使用 promises 吗?
谢谢!
解决方案
如果我很好理解这个问题,你应该在你的方法中返回一个承诺。
function getJSON(url) {
return new Promise(function(resolve, reject) {
const req = https.get(url, res => {
let json = '';
res.on('data', function(chunk) { json += chunk; });
res.on('end', function() { resolve(JSON.parse(json)); });
});
req.on('error', function(err) { console.log(err); });
});
};
const weather = () => {
getJSON('yourURL')
.then((data) => console.log(data))
.catch((error) => console.error(error));
}
推荐阅读
- python - 使用 Python3 读取多行 CSV
- angular - 异步的角度自定义管道
- c++ - 返回 float st(0) 或 xmm0
- excel - 运行支持 VPN 的 Selenium Opera Web 驱动程序
- linux - 在 WSL 中打开应用程序时出现错误消息
- html - CSS 多行链接,可调整下划线粗细以及字母和下划线之间的垂直间距
- angular - 无法在 Azure DevOps for Angular 应用程序中看到覆盖文件夹
- symfony - 暂时禁用学说实体侦听器
- wordpress - 我有一个重力形式放置在同一页面的两个地方
- sql - 百万行表优化 SQL Server