0

I'm consuming an API that returns a famous quote, i wanna grab that quote and consume another api to search for an image related to that quote, but when i make a function that returns the famous quote and call it, it always returns Undefined.

I've tried with promises and async and even timeouts but i haven't been able to return anything.

This is file generate.js

const unirest = require('unirest');

exports.getQuote = function() {
    unirest.get("https://andruxnet-random-famous-quotes.p.rapidapi.com/?cat=movies&count=1")
        .header("X-RapidAPI-Host", "andruxnet-random-famous-quotes.p.rapidapi.com")
        .header("X-RapidAPI-Key", "api-key").then(async (response) => {
            const {quote} = await response.body[0];
            return (quote);
        });
}

quote.js

const middleware = require('../middleware/generate');

router.get('/look',(req,res) => {
    async function call() {
        const quote = await middleware.getQuote()
        setTimeout(function() {
            console.log('quote has: ', quote);
        }, 5000);
    }

    call();

    res.status(200).json({
        message: 'its working'
    });
});

When i call generate.js the output is the quote, but when i call it form the quote.js the output is undefined

Kevin Pastor
  • 761
  • 3
  • 18

1 Answers1

0

Try returning the http.get:

exports.getQuote = function () {
    return unirest.get("https://andruxnet-random-famous-quotes.p.rapidapi.com/?cat=movies&count=1")
        .header("X-RapidAPI-Host", "andruxnet-random-famous-quotes.p.rapidapi.com")
        .header("X-RapidAPI-Key", "api-key").then(async (response) => {
            const { quote } = await response.body[0];
            return (quote);
        });
};
cWerning
  • 583
  • 1
  • 5
  • 15