如何导出要在节点中其他地方重用的承诺

how to export a promise to be reused elsewhere in node

在邮递员中我得到一个错误: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

的承诺的地方
*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()函数。您只是获得了对该函数的引用,但并未实际调用它,因此您没有承诺。

您的变量 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)
    });
  }
}