【问题标题】:Unexpected identifier with await: Node.js [duplicate]带有等待的意外标识符:Node.js [重复]
【发布时间】:2017-11-24 20:38:39
【问题描述】:

我应该查询一个 MongoDB 并找到一个名为 location 的集合的所有元素,并将结果存储在一个变量中。 我有三个脚本:location.js(在 models/location 中)、fetcher.js(在 fetch/fetcher 中>) 和 test.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)

当调用 node 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`

如果我删除 await 关键字,则不会再出现错误,但结果是 Promise { <pending> }

我是 javascript 和 Node.js 的新手,我不掌握异步调用。你能告诉我我错在哪里以及如何解决这个问题吗?

注意:我的版本是Node v8.1.2

【问题讨论】:

  • 嗨@s.dallapalma,你应该在async函数中使用await运算符,await不能单独使用,至少我没有听说过那个用例
  • @ŁukaszSzewczak 回答这个问题,因为你是对的:D
  • @ŁukaszSzewczak await 也出现在 findAll 函数中,那么为什么如果我删除它,结果仍然是“Promise {}”?

标签: javascript node.js mongodb


【解决方案1】:

我解决了。只需在 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 ...
}

【讨论】:

    猜你喜欢
    • 2017-07-02
    • 2018-04-08
    • 2017-06-19
    • 2012-09-23
    • 2017-10-11
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    相关资源
    最近更新 更多