Domanda

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)

È stato utile?

Soluzione

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top