質問

I have a very simple code and the first console.log prints the klout_user.id, but it never prints the second one, ie, klout_response.score. names is an array of twitter screen names. The problem could be as well because of the control flow. I tried running both the klout calls independently and it works. But it does not work in the following code. Any clue ?

names.forEach(function (name, i) { 
    klout.getKloutIdentity(name, function(error, klout_user) {
        if (klout_user.hasOwnProperty("id") && klout_user.id > 0) {
            console.log("klout user", name, "has id : ", klout_user.id); 
            klout.getUserScore(klout_user.id, function(error, klout_response) {
            console.log("klout_user score : ", klout_response.score);
        });
         }
    });
});

I am of the impression that, since it prints the first console.log, the call to getUserScore also should be executed. But it does not. what's wrong ?

役に立ちましたか?

解決

I got the answer by Cojohn at node_klout github page. pasting it here as the answer.


Your code is not retrieving a Klout user score because you're relying on I/O bound functions inside of a for loop. Basically, you're firing off the initial calls to the Klout API, which return normally and print to console, and your process is either finishing or the function is returning before it has a chance to execute klout.getUserScore(). Below is an example of code that will always wait for the response before exiting; note that my test hack is not particularly fast or "asynchronous", it only processes one user at a time and is not suitable for large lists of users. My names and api_key vars have been omitted, you'll need to supply your own.

var klout = new Klout(api_key, "json", "v2");
var events = require("events");

var e = new events.EventEmitter();

e.on("done", function() {
    process.exit();
});

e.on("next", function(i) {
    if (i >= names.length) {
        e.emit("done");
        return;
    }

    console.log("retrieving kloutid for user %s", names[i]);
    klout.getKloutIdentity(names[i], function(error, klout_user) {
        if (error) {
            console.log(error);
            e.emit("next", i+1);
            return;
        }

        if (!klout_user.hasOwnProperty("id") || klout_user.id <= 0) {
            e.emit("next", i+1);
            return;
        }

        console.log("klout user %s has id : %s", names[i], klout_user.id); 

        klout.getUserScore(klout_user.id, function(error, klout_response) {
            if (error) {
                console.log(error);
                e.emit("next", i+1);
                return;
            }

            console.log("klout_user score : %s", klout_response.score);
            e.emit("next", i+1);
        });         
    });
});

e.emit("next", 0);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top