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

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

node.js - Resolving a setTimeout inside API endpoint

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...