CodeFoodPixels / node-promise-mysql

A wrapper for mysqljs/mysql that wraps function calls with Bluebird promises.
MIT License
338 stars 63 forks source link

queries/.then chaining with conditional query at some point #17

Closed DrLightman closed 8 years ago

DrLightman commented 8 years ago

First of all thank you for this module.

Second, I'm newbie at node/promises.

Third, my question, I'm wondering if I'm doing this right:

conn
    .query('select * form ...')
    .then(function (rows) {
        if (rows.length > 0) {
            return conn.query('update ...');
        } else {
            handle0rows();
        }
    })
    .then(function (result) {
        // what is the right code to put here?
        // since this gets executed either way? (rows.length == 0)
        // maybe it suffices an if( result !== undefined ) ... ?
        if (result !== undefined) {
            console.log(result.affectedRows); // of the update
        }
    }).catch(function (err) {
        console.log(err);
    });

Thank you

CodeFoodPixels commented 8 years ago

I'd suggest you have a read of some guides on promises if you're unsure how to use them. Jake Archibald has written one here that may be worth looking at: http://www.html5rocks.com/en/tutorials/es6/promises

DrLightman commented 8 years ago

Thanks for the link. Ignorance is an evli beast.

If you return a value, the next "then" is called with that value. However, if you return something promise-like, the next "then" waits on it, and is only called when that promise settles (succeeds/fails).

So basically without returning anything I'm returning the value "undefined", so my guess to check on (result !== undefined) was correct but driven only by poor experiments.