title: How to make lambda wait for callback?
body: <p>I'm creating an AWS lambda function that is supposed to regularly backup an AppSync API on S3 (it is fired by a CloudWatch schedule rule).
  It's based on a class that, for each API passed as the function args (using environment variables) runs a backup job for each element of the API.</p>
  
  <p>If I run it using only node, it works without any issue.</p>
  
  <p>However, when I deploy or test locally using the serverless framework (<code>serverless deploy</code> and <code>serverless invoke local -f backup</code>), the execution stops at the first asynchronous instruction in a scope other than that of the handler function, whether I use a callback, a Promise.then() or the async/await syntax.</p>
  
  <p>I've considered, running multiple lambda functions for each part of the backup operation, but then I would lose the shared context, which I need to ensure that every part of the backup is done correctly.</p>
  
  <p>In <code>handler.js</code></p>
  
  <pre><code>  // for testing purposes
      // works, waits 5 seconds and execute the rest of the code
      console.log("here1");
      await new Promise(resolve =&gt; setTimeout(resolve, 5000));
      console.log("here2");
      const allBackups = apiIds.map(apiId =&gt; new Backup(apiId));
      allBackups.map(backup =&gt; backup.start());
  </code></pre>
  
  <blockquote>
    <p>Result => 
    here1<br>
    [5 seconds wait]<br>
    here2  </p>
  </blockquote>
  
  <p>However, if I call a function that uses the asynchronous code, such as the <code>start</code> method of the <code>Backup</code> class (in the required <code>Backup.js</code> file), the following happens:</p>
  
  <pre><code>
  
  async start() {
          try {
              console.log("here3");
              const data = await this.AppSync.getGraphqlApi({ apiId: this.apiId }).promise();
              console.log("here4");
  </code></pre>
  
  <blockquote>
    <p>Result =>
    here1<br>
    [5 seconds wait]<br>
    here2<br>
    here3<br>
    End of execution  </p>
  </blockquote>
  
  <p>I have all the required roles, and serverless reports no issues when deploying or invoking locally.</p>
  
  <p>Here is my <code>serverless.yml</code> file:</p>
  
  <pre><code>service:  [name]
  
  provider:
    name: aws
    runtime: nodejs8.10
  
  functions:
    backup:
      handler: handler.backup
      environment:
       [env variables, they are parsed properly]
      timeout: 60
      event:
        schedule: [doesn't work as well, but it's not the issue here]
          name: daily-appsync-backup
          rate: cron(0 0 ** ? *)
          enabled: false
      role: [role]
  </code></pre>
  
  <p>Thanks in advance for your help !</p>