0
我应该查询MongoDB并找到名为位置的集合的所有元素,并将结果存储在变量中。 我有三个剧本:location.js(在型号/位置),fetcher.js(在获取/取出器)和test.js;意外的标识符与等待:Node.js
location.js
const mongoose = require('mongoose')
var Schema = mongoose.Schema
var locationSchema = new Schema({
latitude: String,
longitude: String
})
module.exports = mongoose.model('location', locationSchema)
fetcher.js
const mongoose = require('mongoose')
const Location = require('../models/location')
// set Promise provider to bluebird
mongoose.Promise = require('bluebird')
mongoose.connect('mongodb://localhost:27017/mydb')
exports.findAll = async() => {
let query = await Location.find()
return query
}
test.js
const Location = require('./models/location')
const fetcher = require('./fetch/fetcher')
let items= await fetcher.findAll()
console.log(items[0].latitude)
当调用节点test.js我收到此消息:
let items = await fetcher.findAll();
^^^^^^^
SyntaxError: Unexpected identifier
at createScript (vm.js:74:10)
at Object.runInThisContext (vm.js:116:10)
at Module._compile (module.js:533:28)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3`
如果我删除等待关键字错误好好尝试一下出现了,但结果是Promise { <pending> }
。
我是javascript和Node.js中的新手,我不掌握异步调用。你能告诉我我错在哪里以及如何解决这个问题吗?
注意:我的版本节点V8.1.2
嗨@ s.dallapalma,你应该里面'async'功能,'await'不能单独使用,使用'await'运营商,至少我没听说关于该用例 –
@ŁukaszSzewczak作出回答,因为你是对的:D – robertklep
@ŁukaszSzewczak等待也出现在findAll函数中,为什么如果我删除它,结果仍然是“Promise {}”? –