0

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")
1
  • Are you sure .save() returns a promise when you pass a callback? If not, there's nothing the await will wait for. Commented Nov 15, 2021 at 19:46

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.