异步函数阻止事件循环-调用app.get方法时不呈现页面

时间:2020-02-26 05:49:31

标签: javascript node.js async-await

我有一个crontab,它每隔一个半小时执行一次,这调用了一个异步函数,执行该函数大约需要两分钟。很有可能可以调用app.get方法来呈现网页,但是由于async函数仍在运行,因此该页面未被呈现。为什么会这样呢?一个简单的例子

var cron = require('node-cron');
const express = require("express");

const app = express();

cron.schedule('30 */1 * * *', () => {
    asyncFunction(url);
});

function asyncFunction(url){
// Do some long task!
}

app.get("/", function( req, res ){ 

// It doesn't render while the contrab executes an async
// function. It seems to be blocking the event loop...

res.render('webpageTemplate',{data: data});

});


let port = process.env.PORT;
if( port == null || port == ""){
  port=3000;
} 

app.listen(port, function() {
  console.log("server started at port "+port);
});

0 个答案:

没有答案