简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM