0

I am creating an Excel file with a Lambda function that is later sent by E-Mail. The Excel is filled with data before and is then stored like this(With the excel4node nom package):

console.log("Before print");
    var test2 = await workbook.write(path, function(err, stats) {
        console.log("Excel written");
        if (err) {
          console.error(err);
        } else {
          console.log(stats); // Prints out an instance of a node.js fs.Stats object

        }
      });
    console.log("After print");

The code works sometimes. The problem is the following code is not waiting until the excel is written and the E-Mail cannot find the attachment.

How can I make my Lambda function wait until the excel is written to disk?

jhpratt
  • 6,841
  • 16
  • 40
  • 50
Alex
  • 195
  • 12
  • You probably want to look at [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784/218196) – Felix Kling Nov 16 '18 at 01:11

2 Answers2

5

await only works with functions that return a promise that resolves when the underlying asynchronous operation is complete. Since you are passing a completion-style callback to the function, it likely does not return such a promise.

If the library you are using does not directly support promises, then you can promisify the function yourself.

const util = require('util');
workbook.writeP = util.promisify(workbook.write);

async function someFunc() {
    try {
        let result = await workbook.writeP(path);
        console.log(result);
        // do something here that runs after the .write operation is done
    } catch(e) {
        console.log(e);
    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

I suggest putting the emailing code in the callback, in the else block.

Sergio Flores
  • 439
  • 2
  • 8
  • The better option would be to actually use the `async`/`await` keywords that are part of the language. – jhpratt Nov 16 '18 at 01:25
  • I tried that, but then the Lambda function finishes before the E-Mail is sent – Alex Nov 16 '18 at 01:30