0

I am trying to store the id's from a tweet for later, using the following code:

let twit = require('twit');
let config = require('./config.js');

const T = new twit(config);

let retweetIDs = [];

const promise = T.get('statuses/user_timeline', {screen_name: 'someusername', count: '1'});

promise.then(res =>{
    let id = res["data"][0]["id"];
    retweetIDs.push(id)
});

console.log(retweetIDs)

What the console.log() returns is an empty array [].

While I understand that javascript is asynchronous so the log statement gets executed before a response is returned from the GET request, that is, why it is happenning, I don't understand how to fix it. Any help will be appreciated.

roy05
  • 381
  • 1
  • 2
  • 11
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Tiny Giant Jan 19 '20 at 21:16
  • Just move `console.log` into `promise.then` so `console.log` would be executed after `retweetIDs.push(id)` – Luke Jan 19 '20 at 21:50

1 Answers1

1

Just move console.log into then:

promise.then(res =>{
    let id = res["data"][0]["id"];
    retweetIDs.push(id);
    console.log(retweetIDs);
});

If you are interested in more synchronous code (recommended), try using async-await like this:

let twit = require('twit');
let config = require('./config.js');

(async () => {
    let retweetIDs = [];

    const
        url = 'statuses/user_timeline',
        params = { screen_name: 'someusername', count: '1' },
        result = await new twit(config).get(url, params),
        { id } = result.data[0];

    retweetIDs.push(id);

    console.log(retweetIDs);
})();
Nave Sade
  • 441
  • 2
  • 6
  • Sure but why didn't it work? Typically you want to explain the problem, not just suggest a solution – Ruan Mendes Jan 19 '20 at 21:55
  • @JuanMendes JavaScript is a single threaded language. Therefore, each HTTP request requires a wait. In order not to block the thread, we pass the code that we want to be executed at the end of the HTTP request into callback (this is the what you passed to ```then``` function). Meanwhile, the code continues to run. When the request comes back, it will call to callback you sent to ```then```. Every code you want to run then - push him into the callback. – Nave Sade Jan 23 '20 at 10:04
  • I understand why :) I'm just explaining to you that an answer should not just post some working code, they should explain what the problem was. The explanation belongs in the answer itself, maybe explaining that the line inside the `then` is executed after the function has returned – Ruan Mendes Jan 23 '20 at 13:22