1

What's the most efficient way to send data fetched from within a GET function to a PUG template? I've been pushing the data into an array and then sending that to the template, but this seems inefficient.

app.get('/tweet/:id', function(req, res) {
    const id = req.params.id;
    T.get('statuses/show/' + id, function(err, data, response) {
        let stweet = [];
        stweet.push(data.text);
    });
    res.render('tweet', {stweet: stweet});
});

This gets a Tweet ID from the url and uses it to retrieve the Tweet object. Is there some way I can pull "data" from T.get('statuses/show'...) and display it directly on the PUG template?

Connor D
  • 103
  • 1
  • 9

1 Answers1

1

First of all, your code cannot possible work, since T.get is asyncrhonous & stweet is defined in a scope which res.render('tweet', {stweet: stweet}); does not have access. So that code will throw:

Uncaught ReferenceError: stweet is not defined

T supports promises, you should use them so your code would be a lot cleaner. After T.get is done just send the data directly to the PUG template, there is no need to use: .push

app.get('/tweet/:id', async(req, res) => {

    try {
        // We wait until `T.get` is done
        const { data } = await T.get(`statuses/show/${req.params.id}`, { /** params **/ });    
        res.render('tweet', { stweet: [data.text] });

    } catch(e) {
        // Or whatever error message you want to display
        res.render('error'); 
    }
});

You should check: How do I return the response from an asynchronous call?

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • This seems to always return the error. I can't figure out why that happening. – Connor D May 06 '18 at 15:32
  • "Cannot read property 'base' or undefined". It seems that adding an empty config object gets me around the issue, though. `const { data } = await T.get('statuses/show/' + req.params.id, {});` Thank You! – Connor D May 06 '18 at 15:39