Twilio可编程聊天REST API响应事件

时间:2018-11-21 12:10:53

标签: node.js twilio

 twilioClient.chat.services(service_SID)
.channels
.each(channels => console.log(channels.sid));

从上面的代码中,我如何检查请求是否成功。

我尝试的是:

 twilioClient.chat.services(service_SID)
    .channels
    .each(channels => console.log(channels.sid))
    .then(function (err, docs) {
        if (err) {
            //console.log('error ' + err);
            return res.status(500).send('Problem in retrieving channels');
        }
        res.status(200).json({
            message: 'Channels retrieved sucessfully',
            docs: docs
        });
    })

我需要这样的东西才能知道响应。我需要答应吗?我还不知道诺言。有人可以提供示例或教程吗?

1 个答案:

答案 0 :(得分:0)

这里是Twilio开发人员的传播者。

使用each函数映射到远程资源时,它没有使用Promise。 each希望能工作。但是,您可以为each提供一个函数,一旦请求完成或出现错误,就可以调用该函数。您可以在第二个参数中将该函数作为选项done传递。这是您的操作方式:

twilioClient.chat.services(service_SID)
  .channels
  .each((channel => console.log(channel.sid)), { done: error => {
    if (error) { 
      console.error("There was an error loading the channels.", error);
    } else {
      console.log("All the channels were successfully loaded.")
    }
  });

如果您希望一次性加载频道,那么each可能不是您的正确选择。您也可以使用list来返回频道列表,而不是一次返回一个频道。例如:

twilioClient.chat.services(service_SID)
  .channels
  .list({ limit: 50 }, (error, channels) => {
    if (error) {
      console.error("There was an error loading the channels.", error);
    } else {
      console.log("Here are your channels: ", channels);
    }
  });

让我知道是否有帮助。