1

Why doesn't this work?

Example

var w = new $pnp.Web(baseurl);
var thisfieldid;
w.lists.getByTitle("List").fields.filter("Title eq 'Column1'").get().then(function(data) {
    thisfieldid = data[0].Id;
    console.log("inside:" + thisfieldid);    
});
console.log("outside:" + thisfieldid);

In this Example, the variable thisfieldid is declared outside the pnp method, which makes it global. When I assign a value within the method, shouldn't the value be accessible outside the method? Instead, outside the method it is undefined. Why?

(I think this might be just a javascript issue, but I'm not sure)

  • Can you try using it as this.thisfieldid and see if it works. this.thisfieldid = data[0].Id; – Ram Jul 28 '17 at 3:20
  • Well, I don't see how that could help (using this.thisfieldid inside the method), but I tried it with the same results. If it did work, I'd have to access it outside with w.thisfieldid which also returns undefined. It is the same without the w. – bgmCoder Jul 28 '17 at 3:22
1

The problem isn't that the variable is somehow not global; it's that the pnp functions are running async. The console.log runs before the function finishes and so is blank. That's why there is .then() to keep things running in order within the thread.

var w = new $pnp.Web(baseurl);
var thisfieldid;
w.lists.getByTitle("List").fields.filter("Title eq 'Column1'").get().then(function(data) {
    thisfieldid = data[0].Id;
    console.log("inside:" + thisfieldid);    
}).then(function(){;
     //now that all is finished with the function, do this:
     console.log("outside:" + thisfieldid);
});

console.log("outside:" + thisfieldid); //this fires probably before the function finishes because the function runs async

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.