Reputation: 21
I'm to get the get the data from word document and setting it as global use for my javascript. But I get this error with the following code
you are not able to set the body content to a global variable
var bodyText;
getData();
function getData() {
Word.run(function (context) {
var body = context.document.body;
context.load(body, 'text');
return context.sync().then(function () {
bodyText = body.text;
});
});
console.log(bodyText);
}
console.log(bodyText);
Upvotes: 1
Views: 104
Reputation: 9684
Your first console.log is unreachable code because the method returns before that line is reached. The other problem is that Word.run
is asynchronous and hasn't completed by the time your second console.log is invoked, so the second one returns undefined. The following code works:
var bodyText;
getData();
function getData() {
return Word.run(function (context) {
var body = context.document.body;
context.load(body, 'text');
return context.sync()
.then(function () {
bodyText = body.text;
console.log(bodyText); //Completes second and works
});
});
// console.log(bodyText); // Unreachable code
}
console.log(bodyText); // Completes first and returns undefined
You can get control of the synchronization by putting the second console.log in a then
method that is chained to the call of getData
:
var bodyText;
getData().then(function () {
console.log(bodyText); // Completes second and works
});
function getData() {
return Word.run(function (context) {
var body = context.document.body;
context.load(body, 'text');
return context.sync()
.then(function () {
bodyText = body.text;
console.log(bodyText); //Completes first and works
});
});
}
Upvotes: 2