我在节点7.10:
$ node --version
v7.10.0
我认为它支持await
。
let result = await Weather.findOne(options, function(err, weather) {
if (err) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
}
if (weather) {
res.set('Content-Type', 'application/json');
return res.status(200).send(key + ' already exist.');
}
return weather;
});
console.log(result);
错误讯息:
let result = await Weather.findOne(options, function(err, weather) {
^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:53:10)
at Object.runInThisContext (vm.js:95:10)
at Module._compile (module.js:543:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/app.js:33:15)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.require (module.js:498:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/html/projects/citizen-sense-dustbox-data-streams/es5/v4/bin/www:7:11)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:427:7)
at startup (bootstrap_node.js:151:9)
at bootstrap_node.js:542:3
节点7.10似乎不支持它?或者我做错了什么?
有什么想法吗?
答案 0 :(得分:3)
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await:
await运算符用于等待Promise。 它只能在异步功能中使用。
async function doAwait() {
let result = await Weather.findOne(options, function(err, weather) {
if (err) {
res.set('Content-Type', 'application/json');
return res.status(200).send('Error occurs: ' + err);
}
if (weather) {
res.set('Content-Type', 'application/json');
return res.status(200).send(key + ' already exist.');
}
return weather;
});
console.log(result);
}
答案 1 :(得分:2)
我有v7.10.0,该版本肯定支持await / async。我认为它是在7.4中添加的,但不确定。
ubuntu@ubuntu:~$ node --version
v7.10.0
当我跑步时:
const getDate = async () => {
return new Date()
}
const printDate = async () => {
const date = await getDate()
return date
}
printDate().then(console.log).catch(console.error)
我明白了:
2017-07-04T09:04:27.311Z
编辑: 只是fyi,async / await实际上没有进入ES7。尽管如此,它很可能会成为今年的ECMAScript版本。 https://github.com/tc39/proposals/blob/master/finished-proposals.md