Reputation: 141
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
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