简体   繁体   中英

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")

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")

There is an example in the document

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

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const myBucket = storage.bucket('my-bucket');

const file = myBucket.file('my-file');
const contents = 'This is the contents of the file.';

file.save(contents, function(err) {
  if (!err) {
    // File written successfully.
  }
});

//-
// If the callback is omitted, we'll return a Promise.
//-
file.save(contents).then(function() {});

You don't need to use await, for your example you can try this:

file.save(jsonData.trim(), {resumable : false})
.then(() => nextFunc())
.catch(() => nextFunc())

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

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