在API端点内解析setTimeout [英] Resolving a setTimeout inside API endpoint

查看:125
本文介绍了在API端点内解析setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要添加一个API调用的延迟,所以我使用 setTimeout 。成功2秒后,我需要返回 res.status(200).json(response)

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

我的问题是:我需要调用 resolve 里面的 setTimeout ?或者我可以完全省略吗?

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

推荐答案

您的代码相当于:

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

但只是因为它是一个Express路由处理程序,预计不会返回任何一般内容或承诺

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

另一方面,您的代码:

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

可以调用为:

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

这在短版本中是不可能的。

which wouldn't be possible in the shorter version.

这篇关于在API端点内解析setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆