使用 Promises 傳送 SMS 訊息

Twilio 的 Node.JS API 本身支援 promises,允許你在傳送 SMS 訊息時使用 promises(此示例是直接從 Twilio 的 API Docs 中獲取和調整 )。

// Create an authenticated Twilio REST API client
var twilio = require('twilio');
var client = new twilio.RestClient('ACCOUNT_SID', 'AUTH_TOKEN');

// A simple example of sending an sms message using promises
var promise = client.makeCall({
    to:'+16515556667777', // a number to call
    from:'+16518889999', // a Twilio number you own
    body: 'Hello, world.' // A URL containing TwiML instructions for the call
});

// You can assign functions to be called, at any time, after the request to
// Twilio has been completed.  The first function is called when the request
// succeeds, the second if there was an error.
promise
.then(function(sms) {
    console.log('Call success! SMS SID: ' + sms.sid);
}, function(error) {
    console.error('Call failed!  Reason: ' + error.message);
});