Alex
Alex

Reputation: 195

NodeJS code is not waiting for function completion

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?

Upvotes: 0

Views: 1318

Answers (2)

Sergio Flores
Sergio Flores

Reputation: 539

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

Upvotes: 0

jfriend00
jfriend00

Reputation: 707298

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);
    }
}

Upvotes: 5

Related Questions