节点js中的异步函数完成工作后如何调用函数

时间:2019-07-16 11:48:58

标签: javascript node.js asynchronous

我试图在函数完成工作后调用函数

 invalue.map((val)=>{
               const data = column.map(v=>{ return encryptData.regularDataEncrypt( val[v])});
               const withcote = data.map(x => {return  "'" + x + "'"})   
               const serialnumber_voice =val.serialnumber_voice;   
               const cassdataQuery=`insert into cdr_voice(id,${str},isencrypted) values(now(),${withcote.join()},false)`;
               db.execute(cassdataQuery).then(data=>{
                 pg.query(`update cdr_voice set is_cassandra= true WHERE serialnumber_voice = ${serialnumber_voice}`).then(u=>{
                    console.log("is_cassandra updated",serialnumber_voice )
                 })
                 console.log("data updated ",serialnumber_voice)
               })

            })

我去执行

 function incrementQuaryValue(){

    encryptCdrVoice()

}

完成地图功能后的功能

1 个答案:

答案 0 :(得分:1)

尝试从与map一起使用的回调中返回承诺。

通过这种方式,可以等待使用Promise.all解决所有承诺并在此之后调用encryptCdrVoice

const tasks = invalue.map((val)=>{
    const data = column.map(v=>{ return encryptData.regularDataEncrypt( val[v])});
    const withcote = data.map(x => {return  "'" + x + "'"})
    const serialnumber_voice =val.serialnumber_voice;
    const cassdataQuery=`insert into cdr_voice(id,${str},isencrypted) values(now(),${withcote.join()},false)`;
    return db.execute(cassdataQuery).then(data=>{
        pg.query(`update cdr_voice set is_cassandra= true WHERE serialnumber_voice = ${serialnumber_voice}`).then(u=>{
            console.log("is_cassandra updated",serialnumber_voice )
        })
        console.log("data updated ",serialnumber_voice)
    })

})

Promise.all(tasks).then({
    encryptCdrVoice()
})