asanta27
asanta27

Reputation: 13

How to manipulate Twilio data object? nodeJS

How can I put the info in variable 'data' into the new variable 'newData'?

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

app.get("/results", function(req,res){
   var query = req.query.search
   var newData;

   // Retrieve list of messages
   client.messages.list(query, function(err, data) {
       if(err){console.log(err)} 
       else {
         // Pass info into 'newData'
         newData = data;
       }
   });

console.log(newData);

res.render("results", {data: newData});
});

The above code results in 'newData' being undefined.

If do this:

        else {
         // Render raw 'data'
         res.render("results", {data: data});
       }

The code works fine. However, I want to manipulate the data outside of the function.

Upvotes: 1

Views: 69

Answers (2)

Hunter
Hunter

Reputation: 416

Deals with it being Async. Basically your render is rendering before it has the contents of callback.

Upvotes: 0

user94559
user94559

Reputation: 60143

Move your use of newData into the callback where it's defined:

app.get("/results", function (req,res){
  var query = req.query.search
  var newData;

  // Retrieve list of messages
  client.messages.list(query, function (err, data) {
    if (err) { console.log(err); }
    else {
      newData = data;
      res.render("results", { data: newData });
    }
  });
});

The issue is that newData isn't being populated until the callback runs, but you're trying to use the value before that happens.

Here's your original code with comments explaining what happens in what order:

app.get("/results", function (req,res){
  // 1. This code runs first.
  var query = req.query.search
  var newData;

  // 2. This call is made second.
  client.messages.list(query, function (err, data) {
    // 5. This code runs fifth, after the list call has completed.
    if (err) { console.log(err); }
    else {
      // Pass info into 'newData'
      newData = data;
    }
  });

  // 3. This console.log is third.
  console.log(newData);

  // 4. This runs fourth, at which point the HTTP response has been sent.
  res.render("results", { data: newData });
});

Hopefully that makes it clear why your res.render call belongs inside the callback. You want it to run after the list call has completed.

Upvotes: 1

Related Questions