-2

I made a twitter bot and it's working. But it's a bunch of nested logic that I would like to refactor into functions.

I have this twitter API call and I want to return the reply parameter,

T.get('trends/place', { id: '23424977' }, function(err, reply) {
  // THE WHOLE APP IS BASICALLY IN HERE
{

It won't let me name the function like

T.get('trends/place', { id: '23424977' }, function getTrends(err, reply) {
  // THE WHOLE APP IS BASICALLY IN HERE
{

I messed around with some other ideas but no luck.

The whole bot is here https://glitch.com/edit/#!/trending-mishap?path=server.js

Gaurav Gandhi
  • 3,041
  • 2
  • 27
  • 40
j1mmy
  • 41
  • 6
  • You certainly can name a function in that way (although there's no apparent need to above; but if you defined the function separately and then just gave the API call `getTrends`, *that* would make sense). It's not at all clear what you're asking. Please have a read through [*How do I ask a good question?*](/help/how-to-ask) and use the "edit" link to add details and a specific question. Note that **all** of the relevant code **must** be in the question, not linked; see: [mcve] – T.J. Crowder May 24 '17 at 16:20
  • @T.J.Crowder thank u for the ask a good question link... not(faced) – j1mmy May 24 '17 at 16:29
  • I think this is largely a dup of [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/14220323#14220323). You can't directly and synchronously return the result from an async operation. You have to communicate the result back later using something like a callback or by returning a promise. – jfriend00 May 24 '17 at 16:44

2 Answers2

0

As best as I can understand the question, the issue is that you want to separate out the code inside the callback into separate functions. That's fine, nothing prevents your doing that.

Here's a rough example:

T.get('trends/place', { id: '23424977' }, getTrends);
function getTrends(err, reply) {
   if (err) {
       handleError(err);
       return;
   }
   doSomethingWith(reply);
}
function doSomthingWith(reply) {
   // ...
}

etc., etc.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Move your function out of the .get parameters and then call it in the .get callback, passing it the reply.

var yourSpecialFunction = function(values) {
    // do things here
};
T.get('trends/place', { id: '23424977' }, function(err, reply) {
    if (err) {
        // handle the error
    } else {
        yourSpecialFunction(reply);
    }
}
Ken
  • 466
  • 2
  • 7