0

I'm directly doing await on asynchronous database operations. But the result is nothing. Here, is my code.

var channel_arr = await db.find({type:'pricing'},{channel_name:1},function(err,docs){
        if(err) {
            reject(err)
            return;
        }
        var c = []
        for(var o of docs){
            c.push(o['channel_name'])
        }
        return c;
    })
    alert(channel_arr)

How do I resolve this issue?

bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • You must `await` a promise. And you won't need to pass a callback for that, that's the whole point. – Bergi Jul 20 '17 at 09:10
  • 1
    See [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/1048572) and [why you cannot `return` from arbitrary callbacks](https://stackoverflow.com/q/14220321/1048572?how-to-return-the-response-from-an-asynchronous-call) – Bergi Jul 20 '17 at 09:11

1 Answers1

3

You shouldn't provide callback. You don't need surrounding Promise, instead you will add async function. Approximate code:

async function someJob() {
  try {
    const channel_arr = await db.find({type:'pricing'},{channel_name:1});
    const c = [];
    for (const o of channel_arr) {
      c.push(o['channel_name']);
    }
    return c;
  } catch(e) {
    console.error(e);
    return [];
  }
}

UPDATE: Same code, but using Array.map:

async function someJob() {
  try {
    const docs = await db.find({type:'pricing'},{channel_name:1});
    return docs.map(el => el.channel_name);
  } catch(e) {
    console.error(e);
    return [];
  }
}
Lazyexpert
  • 3,106
  • 1
  • 19
  • 33