Friday, 5 May 2017

Building an array with an asynchronous function then passing the array into a GET method in Node JS

I'm using the Twitter node package for a GET request to retrieve a bunch of tweets. I put all the info I want into an object call 'element' and push into an array call 'ary'. I plan on using this array to dynamically build an ordered list. How would I pass this ary into a webpage so that it would build a new 'ary' every time it loads the webpage and so the server would wait until it gets back the 'ary' before it renders the page. Here's my newbie attempt with little understanding of how to use asynchronous function below. Btw "client" is just a new Twitter() object.

let buildAry = function() {
    let ary = [];
    client.get('search/tweets', {q: '#CSC365'})
        .then(function (tweet) {
            tweet.statuses.forEach(function(item) {
            let element = {
                name : item.user.name, 
                text : item.text,
                pic  : item.user.profile_image_url
            };
            ary.push(element);
        });
    })
    .catch(function (error) {
        throw error;
    })
    return ary;
}

app.get('/profile', function(req, res) {
    res.render('index.pug', buildAry());
});



via zeilmannnoah

No comments:

Post a Comment