node-pg-cursor icon indicating copy to clipboard operation
node-pg-cursor copied to clipboard

Consider adding a Promise for the 'done' state

Open battesonb opened this issue 7 years ago • 1 comments

The .read method would be great if it returned a Promise instead of void to handle all the errors and resolved on the Cursor's 'done' state. I can maybe add this on the weekend if you think it's a valuable addition. Adding it to the current method might be considered "breaking" the API, but no one should be using the return type anyway, so you could reuse the method.

battesonb avatar Feb 02 '18 08:02 battesonb

I would like to use promise too.

For example I would like to use something like this

function pgCursorPromise(cursor, itemNum){
    return new Promise(function(resolve,reject){
        cursor.read(itemNum, (err, rows) => {
            if (err) {
                return reject(err);
            }

            resolve(rows);
        });
    });
}

.....

    const client = await global.pgpool.connect();
    try{
        let rows;
        let totalRows = 0;
        const cursor = client.query(new Cursor('select * from accounts'));
        while ((rows = await pgCursorPromise(cursor, 100)) && rows.length > 0){
            for(let row of rows){
                // do the actual work here
            }
        }
    } catch (err) {
        console.log(err);
    } finally {
        client.release();
    }

goshoo avatar Apr 08 '18 16:04 goshoo