使用 yield 报错
发布于 7 年前 作者 LowLoop 5567 次浏览 来自 问答

var user_info = yield User.findOne({ attributes:[‘id’,‘loginName’,‘loginPasd’], where:{ loginName:userName } }); User是个sequelize模型对象 启动服务后报错: var user_info = yield User.findOne({ ^^^^ SyntaxError: Unexpected identifier at Object.exports.runInThisContext (vm.js:78:16) 请问是怎么回事? 是我 yield 的用法搞错了还是怎的?

15 回复

yield只能在 generator 函数里使用,function * gen() {}

来自酷炫的 CNodeMD

我最外层用了 co(function* () {//code…} 包裹起来了的… 我这样也不行吗?

@LowLoop 那你的 node 版本呢,如果像你写的这样应该是可以的

@hyj1991 node版本 v7.4.0 原本的代码 这样子: co(function* () { router.post(’/’,checkNotLogin, function(req, res, next) { var userName = req.body.inUserName; var userPasd = req.body.inUserPasd;

    var user_info = yield User.findOne({
        attributes:['id','loginName','loginPasd'],
        where:{
            loginName:userName
        }
    });
	//other code......

}).catch(function(e) { console.log(‘错误:’); console.log(e); });

@LowLoop 原因是你在回调函数中使用了 yield ,而你这里的回调函数是一个普通函数,所以不能直接用 yield 并不是最外层包一层 generator 函数就能在里面随意使用的,你的要这样写:

router.post('1', checkNotLogin, co.wrap(function* (req, res, next) {
    var userName = req.body.inUserName;
    var userPasd = req.body.inUserPasd;

    try {
        var user_info = yield User.findOne({
            attributes: ['id', 'loginName', 'loginPasd'],
            where: {
                loginName: userName
            }
        });
    } catch (e) {
        console.error(`错误: ${e}`);
    }
    //other code......
}));

@hyj1991 之前是在执行诸如 findOne之类的方法后面加上 then()方法 来获取返回的值. 但我感觉这样不优雅. 如果是少量的 异步查询还好说…但多了.就太乱了…所以才想着用 co+yield 解决这个问题. 但是我这样写了之后, 启动服务就会报错.我是用的 webstorm11 .

@hyj1991 哦,那我最外层的co(function* () {} 就不需要了是吧

@hyj1991 恩.解决了…谢谢啦.老哥.

@hyj1991 console.error(错误: ${e}); 这里面的 ${e} ${} 是什么表达式吗? 类似jsp 里面的 EL 表达式之类的?

@LowLoop ES6 的字符串模板

yield是中间过渡产品。。。

nodejs最新版已经支持async/await了呀 yield就不要用了

回到顶部