Search code examples
node.jsasynchronousdb2loopbackjs

How do I get the results from a loopback query using find?


I am using nodejs. Using the library loopback-connector to connect to db2 db.

What I am trying to do is to create a cron job to run a specific task. In that task, i am suppose to query the db based on a specific criteria, in this case invCode, And then does some post processing and then updates back to db.

Question 1:

Is this the correct way of getting the result of the query?

Question 2:

My resultList return a Promise results. How to i get the actual values?

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');

const cron = require("node-cron");

var app = module.exports = loopback();

app.start = function() {

    // schedule tasks to be run on the server
    var job1 = cron.schedule("* * * * * * ", function() {
        console.log("---------------------");
        console.log("Running Cron Job 1");

        var Inventory = app.models.Inventory;

        var resultList = Inventory.find({where: {invCode: 'A10231'}})
        .then(function(result){
            return resultList = result;
        })
        .catch(function(err){
            return err;
        });

        console.log("outside!");
        console.log("resultList: " + resultList.value );

    });

    job1.start();

    // start the web server
    return app.listen(function() {
        app.emit('started');

        var baseUrl = app.get('url').replace(/\/$/, '');

        console.log('Web server listening at: %s', baseUrl);

        if (app.get('loopback-component-explorer')) {
            var explorerPath = app.get('loopback-component-explorer').mountPath;
            console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
        }
    });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
    if (err) throw err;

    // start the server if `$ node server.js`
    if (require.main === module) {
        app.start();      
    }
});

Solution

  • The find method is asynchronous and returns a Promise. Actually, your code

    console.log("resultList: " + resultList.value );

    is always executed before this block:

    Inventory.find({where: {invCode: 'A10231'}})
      .then(function(err, inventories) {
        // inventories is a list of Inventory objects, use your data HERE
      })