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

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.