brianc / node-pg-cursor

Query cursor extension for node-postgres
79 stars 30 forks source link

Consider adding a Promise for the 'done' state #37

Open battesonb opened 6 years ago

battesonb commented 6 years ago

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.

goshoo commented 6 years ago

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();
    }