Sen
Sen

Reputation: 19

Google apps script function appenParagraph doesn't append to the end of the document

I have this piece of code and I wonder how to append paragraphs at the end of a recently opened document:

function foo()
{
  var doc = DocumentApp.getActiveDocument();
  var doc_id = doc.getId();
  var body = doc.getBody();

  body.appendParagraph('1');
  body.appendParagraph('2');

  doc.saveAndClose();
  doc = DocumentApp.openById(doc_id);
  body = doc.getBody();

  body.appendParagraph('3');
}

I expected the result was "1 2 3" but it is "3 1 2".

I've been playing with setCursor without success.

Thanks in advance

Upvotes: 0

Views: 631

Answers (1)

EvSunWoodard
EvSunWoodard

Reputation: 1280

In Google Script, functions only actually write when it returns. Every part of the function is just a promise to do all that work at some point, in roughly the same order. I doubt the appendParagraph is the problem. I would expect that it is the doc.saveAndClose() that is causing an error. If you can do so, it is prudent to make each part of this a separate function, called on the onSuccess().

So, when you call foo():

google.script.run
    .withSuccessHandler( function() { google.script.run.bar() })
.foo();

then:

function foo() {
    append 1 & 2
}

function bar() {
    append 3
}

Upvotes: 1

Related Questions