提问者:小点点

无法等待fs.appendfile


在启动Nodejs服务器和终止Nodejs之前,我试图检查是否所有必需的环境变量都存在,如果缺少一些或所有变量。

所以我有一个名为checkvariables.js:

const writeFile = util.promisify(fs.appendFile)

checkDBState()

async function checkDBState(){
    try{
        dbState = process.env.dbState
        if(!dbState){
            console.log(`dbState not Found in the .env file`)
            console.log(`Terminating Server`)
            await errorLogOnFile(`dbState not Found in the .env file`)
            return false
         }
         return true
    }
    catch(err){
        console.log(err)
    }
}

async function errorLogOnFile(errorMessage){
    try{
        let currentDate = new Date()

        let dateTime = currentDate.getMonth()+1 + "/"
        + (currentDate.getDate()+1)  + "/" 
        + currentDate.getFullYear() + " @ "  
        + currentDate.getHours() + ":"  
        + currentDate.getMinutes() + ":" 
        + currentDate.getSeconds(); 
    
        errorMessage = `\n${dateTime} - ${errorMessage} `
        
        await writeFile('errorLog.txt',errorMessage)
        process.exit(1);
        // fs.appendFileSync('errorLog.txt',errorMessage,(err)=>{
        //     if(err) throw err;
        //     process.exit(1);
        // })
    }
    catch(err){
        console.log(err)
    } 
   
   
}

我看到的问题是代码没有等待writefile,一些其他模块在进程写入文件时运行。 因此,在服务器终止之前,我会在其他文件上得到一些错误。 我使用了调试器,发现整个进程在到达writeFile之前都是同步的。 当我明确要求它在继续前进之前等待时,这怎么可能呢?


共1个答案

匿名用户

你好,你觉得这个解决方案怎么样?

async function checkDBState() {
   dbState = process.env.dbState;
   if(!dbState){
     await new Promise((resolve) => {
        let currentDate = new Date();

        let dateTime = currentDate.getMonth()+1 + "/"
        + (currentDate.getDate()+1)  + "/" 
        + currentDate.getFullYear() + " @ "  
        + currentDate.getHours() + ":"  
        + currentDate.getMinutes() + ":" 
        + currentDate.getSeconds(); 

        errorMessage = `\n${dateTime} - ${errorMessage} `;
        fs.appendFileSync('errorLog.txt',errorMessage);
        resolve(console.log('file written'));        
     });
  }
  console.log('this happens after file is written');
}

checkDBState();

输出将为(if(!dbstate)===true):

file written
this happens after file is written

最后,一条金科玉律帮助了我上千次:Async/Await只适用于返回(并解析)承诺的函数