DeceivedRiver
DeceivedRiver

Reputation: 141

Firebase functions not waiting for asynchronous code even with await

I have a firebase function that writes a file to firebase storage:

var tempJSONObject = {
  testing: "why are we testing",
  anothertest: "constanttesting"
}
try {
  const fileName = `storedjokes/81.json`
  const file = bucket.file(fileName);
  console.log('created file');
  const writeStream = fs.createWriteStream(JSON.stringify(file));
  console.log('created write stream');
  var stringy = JSON.stringify(tempJSONObject);
  console.log("stringy created");
  await writeStream.write(stringy, (err) => {
    console.log("writing started");
    if (err) {
      console.log(err.message);
    } else {
      console.log("data written");
    }
  });
} catch (e) {
  console.log('error', e);
}
console.log('post write');

The code execution is fine but the console prints

post write

and never prints

writting started

why is the .write() statement not executing properly, and how is it possible for the code after it to execute before it has finished?

Upvotes: 1

Views: 390

Answers (1)

PotatoParser
PotatoParser

Reputation: 1058

You could wrap the function call around a promise:

var tempJSONObject = {
  testing: "why are we testing",
  anothertest: "constanttesting"
}
try {
  const fileName = `storedjokes/81.json`
  const file = bucket.file(fileName);
  console.log('created file');
  const writeStream = fs.createWriteStream(JSON.stringify(file));
  console.log('created write stream');
  var stringy = JSON.stringify(tempJSONObject);
  console.log("stringy created");
  await new Promise(resolve => {
    writeStream.write(stringy, (err) => {
      console.log("writing started");
      if (err) {
        console.log(err.message);
      } else {
        console.log("data written");
      }
      resolve();
    });
  });
} catch (e) {
  console.log('error', e);
}
console.log('post write');

Upvotes: 2

Related Questions