0

I have the following:

result = foobar(randInt, function(err, result){

})

console.log(result);

whereby the foobar function gets a random response from an external api.

I can output the result if I write the code like this

result = foobar(randInt, function(err, result){
    console.log(result);
    })

and it outputs the result, but if I write it like this

result = foobar(randInt, function(err, result){

    })

    console.log(result);

I get undefined

How can I access the result of the function such that I can process it later

Like this for example result += ' accepted

Koos
  • 117
  • 4
  • 15

1 Answers1

0

This is the problem when you are using callback style functions. It is better to convert them to promise like this

foobar(randInt) {
 return new Promise((resolve, reject) => {
   callyoufunctionhere(randInt, err, result => {
     if(err) reject(err);
     resolve(result);
   });
 }):
}

Now you can use it simply like this

const result = await foobar(randomInt);

Make sure this call us inside a async function.

Ashish Modi
  • 7,529
  • 2
  • 20
  • 35