首页 > 解决方案 > 使用 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 吗?

谢谢!

标签: node.jspromise

解决方案


如果我很好理解这个问题,你应该在你的方法中返回一个承诺。

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));
    }

推荐阅读