简体   繁体   English

SyntaxError:节点中的意外标识符

[英]SyntaxError: Unexpected identifier in node

i try to fetch data from mongodb database using nodejs and mongorito orm for mongodb database, but its show me following error 我尝试使用mongodb数据库的nodejs和mongorito orm从mongodb数据库中获取数据,但它向我显示以下错误

kaushik@root:~/NodeJS/application$ node run.js 
/home/kaushik/NodeJS/run.js:16
        var posts = yield Users.all();
                          ^^^^^
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.runMain (module.js:605:10)
    at run (bootstrap_node.js:423:7)
    at startup (bootstrap_node.js:147:9)
kaushik@root:~/NodeJS/application$ 

here is run.js 这是run.js

var Mongorito = require('mongorito')
var Model = Mongorito.Model

var Users = Model.extend({
    collection: 'testing'// collection name
});
var posts = yield Users.all();
console.log(posts)

i also try 'use strict' but its give following error 我也尝试“使用严格”,但它给出以下错误

SyntaxError: Unexpected strict mode reserved word

Mongorito doesn't use generators ( anymore ), which means you can't use yield (even so, the error you're getting is because yield is only valid inside generator functions, but you're using it at the top level of your code). Mongorito不使用发电机( ),这意味着你不能用yield (即使是这样,你得到的错误是因为yield只有内部生成功能也有效,但你使用它在顶层您码)。 It uses promises now. 现在使用诺言。

If you're willing to use Node v7 (or a transpiler like Babel ), you can use async/await . 如果您愿意使用Node v7(或类似Babel的转译器),则可以使用async/await Your code would look something like this: 您的代码如下所示:

const Mongorito = require('mongorito');
const Model     = Mongorito.Model;
const Users     = Model.extend({ collection: 'test' });

void async function() {
  await Mongorito.connect('localhost/test');
  let posts = await Users.all();
  console.log(posts)
  await Mongorito.disconnect();
}();

Because await only works inside async functions, the above code uses an async IIFE to wrap the code in. 因为await仅在async函数中起作用,所以上面的代码使用异步IIFE来包装代码。

For older versions of Node, you can also use a regular promise chain: 对于旧版本的Node,您还可以使用常规的诺言链:

Mongorito.connect('localhost/test').then(() => {
  return Users.all();
}).then(posts => {
  console.log(posts);
}).then(() => {
  return Mongorito.disconnect();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM