如何在Node.js中利用从MongoDB获取的数据

时间:2018-10-14 22:57:25

标签: javascript node.js mongodb twilio

我已经能够从数据库中获取数据,但是后来我试图利用它,但是它不起作用,

var a = function() {
  first
    .find(
      { url: "https://guarded-everglades-31972.herokuapp.com/getCalls" },
      { url: 1 }
    )
    .then(url => {
      if (!url) {
        return console.log("url not found");
      }
      console.log("Todo by id", url);
    })
    .catch(e => console.log(e));
};

var accountSid = "…";
var authToken = "…";

var client = require("twilio")(accountSid, authToken);

client.calls.create(
  {
    url: a(),
    to: "+2348033260017",
    from: "+1 714 361 9371"
  },
  function(err, call) {
    if (err) {
      console.log(err);
    } else {
      console.log(call.sid);
    }
  }
);

我正在尝试使用从函数中获取的url作为twilio应用程序的url,但这是告诉我我需要提供一个url。

1 个答案:

答案 0 :(得分:0)

您正在异步回调函数中查找URL:

url => {
  if (!url) {
    return console.log("url not found");
  }
    console.log("Todo by id", url);
}

因此,您对a()的调用未返回预期的网址:

client.calls.create(
{
  url: a(), <-- here is the problem
  to: "+2348033260017",
  from: "+1 714 361 9371"
},

相反,您想使用URL inside 回调函数。像这样:

var accountSid = "…";
var authToken = "…";

var client = require("twilio")(accountSid, authToken);

var a = function() {
  first.find(
      { url: "https://guarded-everglades-31972.herokuapp.com/getCalls" },
      { url: 1 })
    .then(url => {
      if (url) {
        client.calls.create({
          url,
          to: "+2348033260017",
          from: "+1 714 361 9371"
        },
        function(err, call) {
          if (err) {
            console.log(err);
          } else {
            console.log(call.sid);
          }
        });
      }
    });
};