2017-06-21 75 views
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

+1

嗨@ s.dallapalma,你應該裏面'async'功能,'await'不能單獨使用,使用'await'運營商,至少我沒聽說關於該用例 –

+0

@ŁukaszSzewczak作出回答,因爲你是對的:D – robertklep

+0

@ŁukaszSzewczak等待也出現在findAll函數中,爲什麼如果我刪除它,結果仍然是「Promise {}」? –

回答

3

我解決。只需在async函數內調用let items= await fetcher.findAll()函數,就像@ŁukaszSzewczak所建議的那樣。所以,我已經更新了我的代碼

async function doSomething(){ 
    let items= await fetcher.findAll() 
    console.log(items[0].latitude) 
    // Other code with variable items here ... 
}