Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await whilst waiting for events - node.js

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

like image 202
Garbit Avatar asked Sep 21 '25 09:09

Garbit


1 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);
    });
}
like image 50
Mark Avatar answered Sep 22 '25 22:09

Mark