我正在关注this示例,但是这部分代码......
const getApiAndEmit = async socket => {
try {
const res = await axios.get(
"https://api.darksky.net/forecast/PUT_YOUR_API_KEY_HERE/43.7695,11.2558"
); // Getting the data from DarkSky
socket.emit("FromAPI", res.data.currently.temperature); // Emitting a new message. It will be consumed by the client
} catch (error) {
console.error(`Error: ${error.code}`);
}
};
我收到以下错误
D:\Documents\js\socketio-server\app.js:42
const getApiAndEmit = async socket => {
^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:542:28)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
at startup (bootstrap_node.js:149:9)
PS D:\Documents\js\socketio-server>
答案 0 :(得分:0)
函数语法似乎正确。您可能需要更新节点,因为async
支持直到今年年初才到达(编辑:google搜索后的7.6版)。
您可以使用promises重写,或者在从命令行运行时尝试--harmony
标志。
答案 1 :(得分:0)
答案 2 :(得分:0)
应该用括号()
const getApiAndEmit = async (socket => {
try {
const res = await axios.get(
"https://api.darksky.net/forecast/PUT_YOUR_API_KEY_HERE/43.7695,11.2558"
); // Getting the data from DarkSky
socket.emit("FromAPI", res.data.currently.temperature); // Emitting a new message. It will be consumed by the client
} catch (error) {
console.error(`Error: ${error.code}`);
}
});