Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...