Victofu
Victofu

Reputation: 53

Use promises to get a JSON file

I'm new to promises and I have a few questions about these.

I needed to get a JSON file (with weather things) for my node.js app from a url so I made a getJSON() function that uses the https module const https = require('https'); that "returns" the file:

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

And as you can see it does not actually returns the value but it resolves it, because i'm calling the function with a promise:

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

So this works, but I feel like it could be way better, could I optimize this ? May I should not even use promises ?

Thanks!

Upvotes: 0

Views: 4733

Answers (1)

Vladimir Krylov
Vladimir Krylov

Reputation: 168

If I understand well this question, you shoud return a promise in your method.

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

Upvotes: 1

Related Questions