模块被缓存
require()
. 所以,第一次加载模块时,模块代码将运行。之后,
module.exports
值已被缓存,前一个结果将立即返回。模块初始化代码将不再运行。所以,第二次加载模块时,第一次创建的承诺会立即返回。
如果您希望每次运行一些代码,您应该导出一个函数,然后您可以在每次运行该函数时调用它。
// myPromise.js
// export a function
module.exports = function() {
return new Promise((resolve, reject) => {
// doesn't run when the endpoint is hit a 2nd time
setTimeout(() => {
console.log('done');
resolve();
}, 3000);
});
}
server.post('/myendpoint', async (req, res, next) => {
// note we are calling the exported function here
const myPromise = require('./myPromise')();
await myPromise;
res.send();
return next();
});