Wait for javascript callback function to finish

I am using google storage api for saving a file in gcp bucket in a async function. I want to wait till I get a error or success in callback, only then I want to proceed with other lines of code but I am getting LastMessage before success or error.

https://googleapis.dev/nodejs/storage/latest/File.html#save

await file.save(jsonData.trim(), {resumable : false}, function(error) {
 if (error) {
   console.log('error');
 } else {
   console.log('success');
 }
})

console.log( "LastMessage: Error or Success is received, only then log this message")

Answer

Your .save() is not returning promise. Rather is giving a callback. You can create a traditional promise method to get what you want to achieve. Here’s the code snippet for that –

const saveFile = (jsonData) => {
    return new Promise((resolve, reject) => {
        file.save(jsonData.trim(), { resumable: false }, function (error) {
            if (error) {
                console.log('error');
                reject()
            } else {
                console.log('sucess');
                resolve()
            }
        })
    })
}

await saveFile()

console.log("LastMessage: Error or Success is received, only then log this message")