我有一个firebase函数,它将文件写入firebase存储:
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');
代码执行良好,但控制台打印
写后
并且从不打印
写入已启动
为什么.write((语句执行不正确,之后的代码如何可能在完成之前执行?
您可以将函数调用包装为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');