문제

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)

도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 sharepoint.stackexchange
scroll top