Loopback: How to use promise with db connectors?

Created on 23 Jan 2018  路  1Comment  路  Source: strongloop/loopback

Hi,

I was using callback with native queries. For example:

const query = 'SELECT * FROM Unit';
dataSource.connector.query(query, [], function(err, units) {
        if (err) {
           callback(err);
           return;
        }
        callback(null, units);
            })

I want to use promise. But I couldn't find how can I use promise for native queries with connector. I tried something like this but couldn't get any result:

   return new Promise(
        function (resolve, reject) {
            dataSource.connector.query(query, [])
                .then(function(units) {
                    resolve(units);
                    });
                })

Do you have any suggestions?

Most helpful comment

I can get result in this way:

function sampleFunc(query) {
    return new Promise(function(resolve, reject) {
        dataSource.connector.query(query, [], function(err, units) {
            if (err) {
                return reject(err);
            }
            return resolve(units);
        });
    });
}

sampleFunc(query).then(function(units) {
    // do something with units
})
.catch(function(err) {
    // do something with err
});

>All comments

I can get result in this way:

function sampleFunc(query) {
    return new Promise(function(resolve, reject) {
        dataSource.connector.query(query, [], function(err, units) {
            if (err) {
                return reject(err);
            }
            return resolve(units);
        });
    });
}

sampleFunc(query).then(function(units) {
    // do something with units
})
.catch(function(err) {
    // do something with err
});
Was this page helpful?
0 / 5 - 0 ratings