0

I have this code which gets values from JSON, parsed into texts, and would like to return text to my chatbot.

rooms: function(){
    var board, text = "Here are the lists of boards, followed by the slug:\n\n";
    Request('https://[redacted]/api/1.0/boards/', function (error, response, body) {
        board = JSON.parse(JSON.minify(body));
        for(var i=0; i<board.length; i++){
            text += board[i].title + ": `" + board[i].slug + "`\n";
        }
        text += "\n Shows the list of topics in specific board with `!fbot view [slug]`";
    });
    console.log(text);
    return text;
}

However, all the text logged and returned is Here are the lists of the boards, followed by the slug, and does not include the parsed JSON.

If JSON parsing gets an error, NPM should be stop, however, it doesn't.

I'm new to NodeJS. Is this about something called async that makes commands not execute in sequential order?

The Request() function used is obtained from https://github.com/request/request.

air cooled
  • 343
  • 1
  • 5
  • 18
srakrn
  • 352
  • 2
  • 16
  • You can't synchronously return a value that is obtained asynchronously. Your function returns BEFORE the async value is even available and your logging is similarly before the value has been obtained. Read the answer you have been marked a dup of for lots of options. This type of question is asked a lot here. Asynchronous callbacks are called sometime later. They are non-blocking so the rest of your function continues to run and return and then sometime later after your function has returned, the async callback is called with the result. Thus, you can't return it the way you are trying to. – jfriend00 Jun 10 '17 at 05:54

1 Answers1

0

As NodeJs behavior is Async and here Request is a promise hence execution comes to the next line as soon as Request line is executed. It will not wait for the callback function of Request to be executed. You may need to rewrite this code as below to make it work.

rooms: function(){
    var board, text = "Here are the lists of boards, followed by the slug:\n\n";
    Request('https://[redacted]/api/1.0/boards/', function (error, response, body) {
        board = JSON.parse(JSON.minify(body));
        for(var i=0; i<board.length; i++){
            text += board[i].title + ": `" + board[i].slug + "`\n";
        }
        text += "\n Shows the list of topics in specific board with `!fbot view [slug]`";
    console.log(text);
    return text;
    }); 
}

This might help

Urvish Kothari
  • 316
  • 2
  • 4