我试图在事件驱动的项目中使用异步等待,我收到以下错误:
tmpFile = await readFileAsync('tmp.png');
^^^^^^^^^^^^^
SyntaxError: Unexpected identifier
到目前为止,我有以下代码(简化):
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();
我的问题并不是真正使用下面的库,而是通过异步等待理解基础知识并在事件驱动的脚本中使用它。我不太明白这是否是一个范围问题或其他问题。
我正在使用以下事件驱动库来创建亚马逊短划线按钮: https://github.com/hortinstein/node-dash-button
谢谢,
安迪
答案 0 :(得分:7)
你有错误功能的异步。它需要回调:
function main() {
dash.on("detected", async function () {
tmpFile = await readFileAsync('tmp.png');
console.log(tmpFile);
});
}
答案 1 :(得分:2)
await
的使用需要在async()
函数中。
async function main() {
return await new Promise(resolve => {
dash.on("detected", async() => {
resolve(await readFileAsync('tmp.png'));
});
})
}
main().then(tmpFile => console.log(tmpFile));
答案 2 :(得分:2)
中直接使用
await
仅影响围绕它的最里面的async
函数 并且只能在async
函数
您的回调应该是async
功能,因为这是直接围绕await
来电的功能。
您的main
功能不一定是async
功能,除非它直接包裹await
来电。