-1

I have simplified my code in nodejs below. I got udefined result because function is async. How do I get valid result, do I have to use promises ?

function findresult() {
    var result;
    setTimeout(function () {
        var result = 2
    }, 1000);
    return result
}
console.log('findresult ' + findresult());//findresult undefined
irom
  • 3,316
  • 14
  • 54
  • 86

2 Answers2

1

You either need to use a simple callback or promise, here's a callback example:

function findresult(callback) {
    var result;
    setTimeout(function () {
        result = 2
        callback(result);
    }, 1000);
    //return result
}

And to use it:

findresult(function(result) {
    console.log("Result is: " + result);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
1

for your example

function findresult(callback) {
    var result;
    setTimeout(function () {
        var result = 2
        callback(result);
    }, 1000);
}
findresult(function(result) {
    console.log('findresult ' + result);
});

you're essentially sending your action as a parameter (the callback) to the function, when the function is done it will give the result to your callback.

in nodejs though, you will usually also want to handle errors, the usual syntax for the callback is function(error, result) (instead of just a result) - if error is null, you can use the result (call succeeded), otherwise it has details of the error.