0

I have a function that makes a request using the request package. What the function should do is return the 'fact'. But when I call the function it returns undefined.

import request from "request";

const catFact = () => {
    
    request('https://catfact.ninja/fact',(error, response, body) => {
    return(body.fact);

});
}

console.log(catFact());
Fisy
  • 19
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – derpirscher Oct 08 '22 at 16:32
  • 1
    No, `catFact` returns nothing. The callback of `request` returns something, but that's totally unrelated to `catFact` – derpirscher Oct 08 '22 at 16:33

1 Answers1

-1

catFact should accept a callback or return a Promise.

You can't work synchronously with asynchronous calls.

Try something like this:

Ex.1:

function catFact(cb) {
    request('https://catfact.ninja/fact', (error, response, body) => {
        cb(body.fact)
    })
}

catFact(console.log)

Ex.2:

function catFact() {
    return new Promise((resolve, reject) => {
        request('https://catfact.ninja/fact', (error, response, body) => {
            if (error) {
                reject(error)
            } else {
                resolve(body.fact)
            }
        })
    })
}

catFact().then(console.log)

Ex.3:

import request from 'request-promise'

async function catFact() {
    const result = await request('https://catfact.ninja/fact')
    return result.fact
}

catFact().then(console.log)
marsgpl
  • 552
  • 2
  • 12
  • I tried the first one but it still returns undefined – Fisy Oct 08 '22 at 16:50
  • @derpirscher My 3rd example suggests using request-promise, that's how. Also linked duplicate provides a mile long answer. – marsgpl Oct 08 '22 at 16:57
  • Suggesting a long deprecated library is not really a benefit. Yes, the linked duplicate provides a long answer which explains the the problem and possible solutions in detail. So if anyone wants to learn something, it's definitely much better then just a few lines of code without any explanation ... – derpirscher Oct 08 '22 at 17:00
  • @derpirscher first 2 lines of my answer contains some explanation. stop lying xd – marsgpl Oct 08 '22 at 17:04