我试图在事件驱动的项目中使用异步等待,并得到以下错误:
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();我的问题不是下面的库,而是理解异步等待的基本原理,并在事件驱动的脚本中使用它。我不太明白这是一个范围界定的问题还是其他问题。
我使用以下事件驱动库作为amazon按钮:https://github.com/hortinstein/node-dash-button
谢谢,
安迪
发布于 2017-10-01 16:36:03
在错误的函数上有异步。它需要在回调:
function main() {
dash.on("detected", async function () {
tmpFile = await readFileAsync('tmp.png');
console.log(tmpFile);
});
}发布于 2017-10-01 16:35:01
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));发布于 2017-10-01 17:09:08
await只影响包围它的最内部的async函数,并且只能直接在async函数中使用。
回调应该是async函数,因为这是直接围绕await调用的函数。
您的main函数不需要是async函数,除非它直接包装await调用。
https://stackoverflow.com/questions/46514451
复制相似问题