1

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.

1 Answer 1

2

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())  
}
Sign up to request clarification or add additional context in comments.

8 Comments

When you create a promise, you need to pass two callbacks, a resolve and a reject. You need to call the resolve with the results when everything is ok, and call reject with the error when it goes wrong
if your async function only returns await, you don't need async await at all. Just pass through the promise. async function send(){ return await get_all_channels() } becomes function send(){ return get_all_channels() }, which can be deleted
So,how do you do that? This promise thing is very confusing for me @netchkin
@bigbounty I have modified my comment, if you have any questions regarding promises, feel free to ask them :)
@bigbounty: you can use directly get_all_channels function whereever you need. You just need to take into account the call context - if you call get_all_channels from an async function, you should do const channels = await get_all_channels(). If you call it from a sync function, then you need to use .then() or catch() to react on the result of get_all_channels
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.