Home > Software design >  How to synchronize asynchronous calls to Slides api and Slides class built in App Script?
How to synchronize asynchronous calls to Slides api and Slides class built in App Script?

Time:10-04

I am trying to create a slide in Google App Script and then add a text box to this newly created slide. The first call is to the Slides api and the second call is made using inbuilt methods. However, because of the asynchronous nature of these two lines, the 2nd is operating before the 1st and causing an obvious error.

Slides.Presentations.batchUpdate({'requests': requests}, presentationId);
var shape = presentation.getSlideById(newpageId).insertShape(SlidesApp.ShapeType.TEXT_BOX, 0, 0, width, height/4);

My question would be: How to create a callback or use a promise to make the needed adjustments?

CodePudding user response:

I tried a different approach, I grouped all the request in chronological order and it worked:

 var requests = [{
    'createSlide': {
      'objectId': newpageId,
      'insertionIndex': current_index,
      'slideLayoutReference': {
        'predefinedLayout': 'BLANK'
      }
    }
  },
  {
    "createShape": {
      "objectId": `silaComment${questionNumber}${token}`,
      "elementProperties": {
        "pageObjectId": newpageId,
        "size": {
          "width": {
            "magnitude": 3000000,
            "unit": "EMU"
          },
          "height": {
            "magnitude": 3000000,
            "unit": "EMU"
          }
        },
        "transform": {
          "scaleX": 0.6807,
          "scaleY": 0.4585,
          "translateX": 6583050,
          "translateY": 1673950,
          "unit": "EMU"
        }
      },
      "shapeType": "WAVE"
    }
  },
  {
    "insertText": {
      "objectId": `silaComment${questionNumber}${token}`,
      "text": comment   '\nasked by '   name,
      "insertionIndex": 0
    }
  }]; 
Slides.Presentations.batchUpdate({'requests': requests}, presentationId);

CodePudding user response:

You could simply wait:

Utilities.sleep();

But this requires estimating the api call execution time.

Apps script currently doesn't support promises. Even if it did, the batchUpdate call to the api doesn't return a promise.

  • Related