异步等待事件等待 - node.js

Gar*_*bit 1 javascript asynchronous node.js async-await

我试图在事件驱动的项目中使用异步等待,我收到以下错误:

tmpFile = await readFileAsync('tmp.png');
                ^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
Run Code Online (Sandbox Code Playgroud)

到目前为止,我有以下代码(简化):

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();
Run Code Online (Sandbox Code Playgroud)

我的问题不是真正使用下面的库,而是通过异步等待理解基础知识并在事件驱动的脚本中使用它.我不太明白这是否是一个范围问题或其他问题.

我使用以下事件驱动库来创建亚马逊短划线按钮:https: //github.com/hortinstein/node-dash-button

谢谢,

安迪

Mar*_*yer 8

你有错误的功能异步.它需要在回调上:

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

  • 我只有一个快速回答,因为当我开始使用async/await时,我做了完全相同的事情. (2认同)
  • 我希望我只是用谷歌搜索这个而不是花几个小时试图弄清楚它!互联网是有史以来发明的最好的宝石。我打赌你根本不记得你发过这个!太感谢了。 (2认同)