0

I have a bit of a problem with my callback function. The flow of the code looks like this:

  • Call queryDB()
  • QueryDB gets data from an API and invokes the callback
  • Callback returns data
  • Print data on screen
//index.js
console.log(dscAPI.queryDB(dscDB, 'recent'));

and the functions

function getRecent(dscDB, callback) {
    const query = 'year=' + new Date().getFullYear();;
    const params = {
        type: 'master',
        per_page: '10'
    }

    dscDB.search(query, params)
        .then(function(data) {
           callback(data.results); 
        })
        .catch((err) => console.log(err));
}

function returnRecent(data) {
    console.log(data); //returns desired output
    return data; //returns undefined
}

module.exports = {
    queryDB: function(dscDB) {
        getRecent(dscDB, returnRecent);
    }
}

The issue is: callback returns undefined, even before console.log(). I have been trying using async/await to make it wait for the value, but it didn't seem to be able to do that. I read this article: https://github.com/maxogden/art-of-node#callbacks, and I structured my code similar way, but to no avail. Maybe you have any ideas how should I handle that?

malpa222
  • 43
  • 1
  • 5
  • Your callback function doesn't have a conventional callback signature. In Node it's preferred to be `(err, result...)` where `err` is *always* first. – tadman Oct 26 '20 at 17:33
  • 1
    Are you sure you want a callback solution here? It's 2020, `async` and `await` are established things, and you're using Promises, so why not just do it the simple way? – tadman Oct 26 '20 at 17:35
  • "`return data; //returns undefined`" — No, it doesn't. You aren't looking at the return value. It returns to the left of `callback(data.results);` – Quentin Oct 26 '20 at 17:35
  • 1
    The return value of callback functions are typically ignored, as in thrown in the trash. Remember: Callback functions, from the perspective of the computer, **happen in the distant future**, long after immediate function calls like `console.log` have wrapped up. If you think `queryDB` returns something useful, you're mistaken. It doesn't. – tadman Oct 26 '20 at 17:35

0 Answers0