0

In my code :

    var Helper = require('./helper.js');
    var helper = new Helper();

    var Crawler = function(){   

        var me = this;

        this.getListCategory = function(){

            var listCategory = helper.categoryInMenu(1, function(err, result){
                console.log(result); //1. display command : object
                return result;
            });

            console.log(listCategory); //2. display command : undefined

        }
    }

    module.exports = Crawler;

At 1 : display command is object.

At 2 : display command is undefined.

Why my variable listCategory is undefined ?

How to : do listCategory is result of helper.categoryInMenu at 2 ?

Anh NC
  • 47
  • 10
  • 2
    You can't rely on `return` in an async callback. See: [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call). – Mulan Jul 16 '15 at 04:25
  • Your ideal : use callback ? I want use variable in medthod, don't want use callback in callback in callback ....v....v... – Anh NC Jul 16 '15 at 04:32
  • i'll set variable `this.listCategory`, then set it = return `this.getListCategory`. And use variable `this.listCategory` in some Method Other. – Anh NC Jul 16 '15 at 04:35
  • That won't work either because `this.listCategory` will be `null` until your callback sets it. If you're unhappy with nesting "callback in callback in callback ..." there's a wide variety of solutions to your "problem" as linked in that post. Your problem is the among the most popular problems people have when they start async programming. That's why that question has so many upvotes. I don't mean to sound rude, but there is nothing special about your problem. If you fail to be patient and learn from the examples provided, there would be no benefit from other answers provided to this question. – Mulan Jul 16 '15 at 04:44
  • @naomik : you are a teacher ? :v . i think my english is bad, so i learn example by code, not read some text. i'll try :) thanks u ! – Anh NC Jul 16 '15 at 06:49

1 Answers1

0

You want to use your method getListCategory synchronously but by the time the result categoryInMenu method returns, your method getListCategory will be done, since categoryInMenu method is going to be executed asynchronously, so you can't use return.

So to return a result from your getListCategory, you could use callbacks:

var helper = {
  categoryInMenu: function(number, cb) {
    setTimeout(function() {
      cb(null, 'list category');
    }, 2000);
  }
};

var crawler = {
  getListCategoryMenu: function(cb) {
    helper.categoryInMenu(1, function(err, result) {
      cb(err, result);
    });
  }
};

crawler.getListCategoryMenu(function(err, result) {
  console.log(result); // outputs: 'list category'
});
Wilson
  • 9,006
  • 3
  • 42
  • 46