-1
async function count() {
        let nedb = <<functional nedb database>>
        let count = 0
        await iterate(nedb, {}, g=>{
            count++
        })
        console.log(count)


iterate(xx, query, callback) {
    return new Promise((res, rej)=> {
        pkgs.find(query).exec((err, res)=>{
            if(err!==null) {
                this.err(err)
            } else {
                res.forEach((pkg)=>{
                    callback(pkg)
                })
            }
        })
        res()
    })

I would like to write something, after the iteration is over, is there way to do it in some normal way?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
m23
  • 91
  • 1
  • 3

1 Answers1

0

You need to put the res()olve call inside the find callback. Immediately fulfilling the promise to undefined won't help.

But you really shouldn't pass an iteration callback at all. Instead, write

async function count() {
    let nedb = …;
    let count = 0;
    const pkgs = await query(nedb, {});
    pkgs.forEach(pkg => count++);
    // or maybe better just:
    const count = pkgs.length;
    console.log(count);
}

function query(pkgs, query) {
    return new Promise((resolve, reject)=> {
        pkgs.find(query).exec((error, result)=>{
            if (error !== null) reject(error);
            else resolve(result);
        });
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375