Async await whilst waiting for events - node.js

Viewed 7888

I'm trying to use async await within an event driven project and I am getting the following error:

tmpFile = await readFileAsync('tmp.png');
                ^^^^^^^^^^^^^
SyntaxError: Unexpected identifier

So far I have the following code (simplified):

const fs = require('fs');
const dash_button = require('node-dash-button');
const dash = dash_button(process.env.DASH_MAC, null, 1000, 'all');

function readFileAsync (path) {
    return new Promise(function (resolve, reject) {
        fs.readFile(path, function (error, result) {
            if (error) {
                reject(error);
            } else {
                resolve(result);
            }
        });
    });
};

async function main() {
    dash.on("detected", function () {
        tmpFile = await readFileAsync('tmp.png');
        console.log(tmpFile);
    });
}

main();

My issue isn't really with the library below but rather understanding the fundamentals with async await and using it within an event driven script. I don't quite understand if this is a scoping issue or something else.

I am using the following event driven library for an amazon dash button: https://github.com/hortinstein/node-dash-button

Thanks,

Andy

3 Answers

You have your async on the wrong function. It needs to be on the callback:

function main() {
    dash.on("detected", async function () {
        tmpFile = await readFileAsync('tmp.png');
        console.log(tmpFile);
    });
}

Use of await needs to be within an async() function.

async function main() {
    return await new Promise(resolve => {
                   dash.on("detected", async() => {
                     resolve(await readFileAsync('tmp.png'));
                   });
                 })
}

main().then(tmpFile => console.log(tmpFile));

await only affects the innermost async function that surrounds it and can only be used directly inside async functions

Your callback should be an async function as that is the function directly surrounding your await call.

Your main function need not be an async function unless it wraps an await call directly.

Related