javascript - 如何导出 promise 以在 Node 中的其他地方重用

标签 javascript node.js express promise es6-promise

在 postman 中,我收到错误:TypeError: ClientPromise.then is not a function。

*auth.js*

const Client = require("@x/nr");

module.exports = {
  ClientPromise: function(options) {
    return Client.authenticate(options); <--- (this returns a promise)
  }
}

这里是我想调用 auth.js promise 的地方

*API.js*
var ClientPromise = require('../config/auth').ClientPromise

module.exports = {
  findOneClientProblem: function(req, res) {
    ClientPromise.then(function (client) {
      const Problem = client.Problem;
      return Problem.findOne(req.params.radarProblemID)
    }).then(function (result){
      return res.json(result)
    });
  }
}

当我将所有内容都放在像这样的一个文件中时,它就可以工作。

const Client = require("@x/nr");

const ClientPromise = Client.authenticate(options); <--- (this returns a promise)

module.exports = {
  findOneClientProblem: function(req, res) {
    ClientPromise.then(function (client) {
      const Problem = client.Problem;
      return Problem.findOne(req.params.radarProblemID)
    }).then(function (result){
      return res.json(result)
    });
  }
}

最佳答案

在 API.js 中,您必须实际调用 ClientPromise() 函数。您只是获得了对该函数的引用,但并未实际调用它,因此您没有 promise 。

您的变量ClientPromise仅包含对函数本身的引用。要执行该函数,您需要调用它:

ClientPromise(options).then(...)

这是上下文的变化:

// *API.js*
var ClientPromise = require('../config/auth').ClientPromise

module.exports = {
  findOneClientProblem: function(req, res) {
    ClientPromise(/* put options here */).then(function (client) {
      const Problem = client.Problem;
      return Problem.findOne(req.params.radarProblemID)
    }).then(function (result){
      return res.json(result)
    });
  }
}

关于javascript - 如何导出 promise 以在 Node 中的其他地方重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37442315/

相关文章:

javascript - Django 管理员 : Pre-populating values from POST or GET?

javascript - 通过 AJAX 使用单个提交按钮提交多个 HTML 表单

javascript - 使用 jquery 单击时如何更改文本的颜色?

javascript - Node JS : How to Promise For Loop

JavaScript 模块模式 - protected 成员?

javascript - ASP.NET Core 和 Node.js 的相似之处

javascript - 在二级链接中循环信息

javascript - Unity3d和Sockets.IO不会握手

node.js - 服务器错误以 express 方式发送给客户端

node.js - 在 Webstorm 2017.1.3/Ubuntu 16.04 LTS 中安装 npm 包