0

I need to add a delay to an API call so I'm using setTimeout. After 2 seconds on success, I need to return res.status(200).json(response).

  exports.someEndpoint = function(req, res) {
    return request.post({
      url: //etc
    })
    .then(function(response) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          // is this right?
          resolve(
            res.status(200).json(response);
          );
        }, 2000);
      });
    });
  };

My question is: do I need to call resolve inside the setTimeout? Or can I just completely omit it?

cusejuice
  • 10,285
  • 26
  • 90
  • 145

2 Answers2

2

Your code is equivalent to:

  exports.someEndpoint = function(req, res) {
    return request.post({
      url: //etc
    })
    .then(function(response) {
        setTimeout(function() {
            res.status(200).json(response);
        }, 2000);
    });
  };

But only because it is an Express route handler that's not expected to return anything in general or a promise in particular.

On the other hand your code:

  exports.someEndpoint = function(req, res) {
    return request.post({
      url: //etc
    })
    .then(function(response) {
      return new Promise(function(resolve, reject) {
        setTimeout(function() {
          // is this right?
          resolve(
            res.status(200).json(response);
          );
        }, 2000);
      });
    });
  };

could be called as:

yourModule.someEndpoint(req, res).then(function () {
  // code to run after the timeout
});

which wouldn't be possible in the shorter version.

rsp
  • 107,747
  • 29
  • 201
  • 177
0

Do I need to call resolve inside the setTimeout?

It depends on what is going to happen with exports.someEndpoint, but usually yes - you would want to return a Promise that has completed all async operations in it's fulfilled state.

For example if your express handler is being captured by a function that expects a promise, then the flow will continue, before you have returned a response to your user.

If you don't care about promises in your request handler, then you can also not return request.post({ and just return nothing.

drinchev
  • 19,201
  • 4
  • 67
  • 93