bigbounty
bigbounty

Reputation: 17408

Using async/await not working

I have a function and it does async db search operation.

var get_all_channels = function {
    return new Promise(()=> {
        db.find({type:'pricing'},{channel_name:1},function(err,docs){
        if(err)
            return err;
        var c = []
        docs.forEachOf(function(ch){
            c.push(ch['channel_name'])
        })
        return c;
    })
    })
}

async function send(){
    return await get_all_channels()
}
function calculate(){
    send().then(res => alert(res))    
}

Here, the above function is not working. I don't know why? Please help me fix this function.

Upvotes: 1

Views: 1056

Answers (1)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

You need to resolve the promise with the results, the array c, in get_all_channels:

var get_all_channels = function {
    return new Promise((resolve, reject)=> {
        db.find({type:'pricing'},{channel_name:1},function(err,docs){
        if(err) {
            reject(err)
            return
        }

        var c = []
        docs.forEachOf(function(ch){
            c.push(ch['channel_name'])
        })

        resolve(c)
    })
    })
}

And in calculate, you can also use await if you want, and, as pointed by @netchkin, you don't need the async/await in send as long as it just returns the await:

function send(){
   return get_all_channels()
}

async function calculate(){
   alert(await send())  
}

Upvotes: 2

Related Questions