Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
424 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...