简体   繁体   中英

Server endpoint only runs promise function the first call, returns immediately after

(I am using Restify instead of Express if that makes a difference.)

This works as expected every time the endpoint is hit:

server.post('/myendpoint', (req, res, next) => {
    setTimeout(() => {
        console.log('done');
        res.send();
        return next();
    }, 3000);
});

This only works the first time the endpoint is hit, then immediately returns when it is hit again without running the promise (no console.log is seen):

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

I would imagine this code is pretty much the same. Am I missing something?

Modules are cached by require() . So, the first time you load your module, your module code will run. After that, the module.exports value has been cached and the previous result will just be returned immediately. Your module initialization code will not run again. So, the 2nd time you load your module, the promise that you created the first time is just returned immediately.

If you want some code to run each time, you should export a function and then you can call that function each time you want it to run.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM