服务器端点仅在第一次调用时运行 promise 函数,returns 之后立即运行
Server endpoint only runs promise function the first call, returns immediately after
(如果有区别的话,我正在使用 Restify 而不是 Express。)
每次命中端点时都按预期工作:
server.post('/myendpoint', (req, res, next) => {
setTimeout(() => {
console.log('done');
res.send();
return next();
}, 3000);
});
这仅在第一次命中端点时有效,然后在没有 运行 承诺的情况下再次命中时立即 returns(没有看到 console.log):
// myPromise.js
module.exports = 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) => {
const myPromise = require('./myPromise');
await myPromise;
res.send();
return next();
});
我想这段代码几乎是一样的。我错过了什么吗?
模块由 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();
});
(如果有区别的话,我正在使用 Restify 而不是 Express。)
每次命中端点时都按预期工作:
server.post('/myendpoint', (req, res, next) => {
setTimeout(() => {
console.log('done');
res.send();
return next();
}, 3000);
});
这仅在第一次命中端点时有效,然后在没有 运行 承诺的情况下再次命中时立即 returns(没有看到 console.log):
// myPromise.js
module.exports = 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) => {
const myPromise = require('./myPromise');
await myPromise;
res.send();
return next();
});
我想这段代码几乎是一样的。我错过了什么吗?
模块由 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();
});