我如何让它在"Ex It"之前.log "Read It" conosle?


app.get('/', async (req, res) => {
await fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
data = d
console.log("Read It")
// console.log(data)
});
console.log("Ex It")
res.render('website/index', { 'data': data });
});

我试着使用async函数并等待,但当我运行它时,它是控制台记录的";Ex It";在";阅读它";。它如何使它输出";阅读它";在";Ex It"?

您可以按照注释的建议使用promise版本"CCD_ 1";

app.get('/', async (req, res) => {
data = await fs.promises.readFile('./views/website/index.html', 'utf8');
console.log("Read It")
console.log("Ex It")
res.render('website/index', { 'data': data });
});

或者把所有的东西都放回

app.get('/', async (req, res) => {
fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
data = d
console.log("Read It")
console.log("Ex It")
res.render('website/index', { 'data': data });
});
});

或者你可以用承诺来包装回调

app.get('/', async (req, res) => {
await new Promise((resolve, reject) => {
fs.readFile('./views/website/index.html', 'utf8', (err, d) => {
data = d
console.log("Read It")
resolve();
});
});
console.log("Ex It")
res.render('website/index', { 'data': data });
});

或者使用同步版本(实际上不要这样做(

app.get('/', async (req, res) => {
data = fs.readFileSync('./views/website/index.html', 'utf8');
console.log("Read It")
console.log("Ex It")
res.render('website/index', { 'data': data });
});

最新更新