Javascript 服务端点仅在第一次调用时运行promise函数,然后立即返回

Javascript 服务端点仅在第一次调用时运行promise函数,然后立即返回,javascript,node.js,restify,Javascript,Node.js,Restify,(如果有什么不同的话,我使用的是Restify而不是Express。) 每次命中端点时,此操作都会按预期工作: server.post('/myendpoint', (req, res, next) => { setTimeout(() => { console.log('done'); res.send(); return next(); }, 3000); }); 这仅在第一次命中端点时有效,然后在再次命中端点时立

(如果有什么不同的话,我使用的是Restify而不是Express。)

每次命中端点时,此操作都会按预期工作:

server.post('/myendpoint', (req, res, next) => {
    setTimeout(() => {
        console.log('done');
        res.send();
        return next();
    }, 3000);
});
这仅在第一次命中端点时有效,然后在再次命中端点时立即返回,而不运行promise(未看到console.log):


我可以想象这段代码几乎是一样的。我缺少什么吗?

模块由
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();
});
// 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();
});