1

I am trying to perform sql queries based on the callback results in if conditions but i am unable to write the code .so please provide som information in code

app.get('/resell-property', function(req, res) {
        var data = {}
        data.unit_price_id = 1;
        function callback(error, result) {
            if (result.count == 0) {
                return hp_property_sell_request.create(data)
            }
            else if (result.count > 0) {
                return hp_unit_price.findAll({
                    where: {
                        unit_price_id: data.unit_price_id,
                        hp_property_id: data.property_id,
                        hp_unit_details_id: data.unit_details_id
                    }
                })
            }
        }


        hp_property_sell_request.findAndCountAll({
            where: {
                unit_price_id: data.unit_price_id
            }
        }).then(function (result) {
            if (result) {
                callback(null, result);
            }
        });


    });

In this how can i write the callbacks for

hp_property_sell_request.create(data) ,hp_unit_price.findAll({
                    where: {
                        unit_price_id: data.unit_price_id,
                        hp_property_id: data.property_id,
                        hp_unit_details_id: data.unit_details_id
                    }
                })

In that after returning result again i have to handle callbacks and perform this query

if(result.request_id){
               return hp_unit_price.findAll({
                    where:{
                        unit_price_id:result.unit_price_id,
                        hp_property_id:result.property_id,
                        hp_unit_details_id:result.unit_details_id
                    }
                }).then(function (result){

                    if(result.is_resale_unit==0 && result.sold_out==0){
                        return Sequelize.query('UPDATE hp_unit_price SET resale_unit_status=1 WHERE hp_unit_details_id='+result.unit_details_id+' and  hp_property_id='+result.property_id)
                    }

                })
            }

3 Answers 3

2

The promise resolve function takes only one input argument, so if you need to pass in multiple stuff, you have to enclose them in a single object. Like, if you have to go with something like:

database.openCollection()
    .then(function(collection){
        var result = collection.query(something);
        var resultObject = { result: result, collection: collection };
    })
    .then(function(resultObject){
        doSomethingSyncronousWithResult(resultObject.result);
        resultObject.collection.close();
    });

You can't use Promise all if all of your stuff isn't a result of a promise resolve, you might need to go with something like this.

Disclaimer: The code example is a very poor one, but it explains the concept.

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

1 Comment

thanq for the reply @ardil please give some sample code
2

I would suggest you to learn about Promises, particularly Bluebird. You can promisify traditional callback methods.

I would also create model level functions in different files. Here's an example.

parent.js

const db = require("./connections/database");  // connection to database

const getChildForParent = function (parentId, childId, callback) {
    db.find({parent: parentId, child_id: childId}, "childrenTable", function(err, result) {
        if (err) {
            return callback(err);
        }
        return callback(null, result);
    });
};

children.js

const db = require("./connections/database");  // connection to database

const getToysForChild = function (childId, callback) {
    db.find({toy_belongs_to: parentId}, "toysTable", function(err, result) {
        if (err) {
            return callback(err);
        }
        return callback(null, result);
    });
};

Then in controller you can do something like this:

const Bluebird = require("bluebird");
const Parent = require("./parent.js");
const Child = require("./child.js");

// Promisifying adds "Async" at the end of your methods' names (these are promisified)
Bluebird.promisifyAll(Parent); 
Bluebird.promisifyAll(Child);

// Just an example.
app.get("/parent/:parentId/children/:childId", function(req, res) {
    return Bluebird.try(function() {
         return User.getChildForParentAsync(req.params.parentId, req.params.childId);
    }).then(function(child) {
       return Child.getToysForChildAsync(child.child_id);
    }).then(function(toys) {
       // Do something with toys.
    });
});

Of course you can do much more with this and this is not the only way.

Also you can use Promise.all(). This method is useful for when you want to wait for more than one promise to complete.

Let's say you have a list of urls that you want to fetch and process the results after all the data has been fetched.

var urls = [url1, url2, url3, url4, url5 .......... ];
var Bluebird = require("bluebird");
var request = require("request"); // callback version library

Bluebird.promisifyAll(request);

// create a list which will keep all the promises
var promises = [];

urls.forEach(function(url) {
    promises.push(request.getAsync(url1));
});

// promises array has all the promises
// Then define what you want to do on completion.

Bluebird.all(promises).then(function(results) {
    // results is an array with result a url in an index

    // process results.
});

Comments

1

I would recommend to use Promises to solve that. If you need all results of all Requests, when they are all done Promise.all() will do that for you. Your basic could look like that:

var req1 = new Promise(function(res, rej){
    var req = new XMLHttpRequest()
    …
    req.addEventListener('load', function (e) {
        res(e);
    })

var req2 = //similar to the above

Promise.all([req1, req2, …]).then(function(values){
  //all requests are done here and you can do your stuff
});

You can also use the new fetch api, which creates Promises like so:

var req1 = fetch(…);
var req2 = fetch(…);
Promise.all([req1, re2, …]).then(…);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.