开发者问题收集

Firebase 函数即使使用 await 也不会等待异步代码

2020-08-21
383

我有一个 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');

代码执行正常,但控制台打印

post write

并且从不打印

writting started

为什么 .write() 语句无法正确执行,以及它之后的代码如何在它完成之前执行?

1个回答

你可以将函数调用包装在一个承诺中:

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');
PotatoParser
2020-08-21