简体   繁体   中英

Node.js callback confusion

I am trying to implement an autocompleter on a nodejs app using nowjs.

everyone.now.sendAutocomplete = function(search) {  
  var response = getAutocomplete(search);
  console.log("response");
  console.log(response);
};

which calls:

function getAutocomplete(search) {
    console.log(search);
    var artist = new Array();

    request({uri: 'http://musicbrainz.org/ws/2/artist/?query=' + search + '&limit=4', headers: "Musicbrainz Application Version 1"}, function(error, response, body) {
        par.parseString(body, function(err, result) {
            var count = result['artist-list']['@']['count'];

            var artists = result['artist-list']['artist'];
            // var artist = new Array();

            if (count > 1) {
            artists.forEach(function(a) {
                var att = a['@'];
                var id = att['id'];
                var name = a['name'];
                var dis = a['disambiguation'];

                if (dis) {
                    var display = name + " (" + dis + " )";
                } else {
                    display = name;
                }
                artist.push({'id':id, 'name': name, 'disambiguation':dis,
                                     'label':display, 'value':name, 'category':"Artists"});
            });
            //everyone.now.receiveResponse(artist);
            console.log("artist");
            console.log(artist);
            return artist;
        } else {
            console.log(artists);
            var att = artists['@'];
            var id = att['id'];
            var name = artists['name'];
            var dis = artists['disambiguation'];
            var resp = [{'id':id, 'name': name, 'disambiguation':dis,
                                 'label':name, 'value':name, 'category':"Artists"}];
            return resp;
            // everyone.now.receiveResponse([{'id':id, 'name': name, 'disambiguation':dis,
            //                       'label':name, 'value':name, 'category':"Artists"}]);
        }

        });
    });
}

However, console.log(response) says that response is undefined. I am new to node so the answer is probably simple, but still can't figure it out.

You are treating the async call as synchronous. Your getAutocomplete needs to take a callback function to get the response. You're using that a lot already, in your request call and your parseString call.

Like this:

everyone.now.sendAutocomplete = function(search) {  
    getAutocomplete(search, function (response) {
        console.log("response");
        console.log(response);
    });
};

And instead of return :

function getAutocomplete(search, callback) {
    // ...
    callback(result);
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM