eggjs 在定时器访问service提示Cannot read property 'service' of undefined
update_article.js(schedule目录下):
const Subscription = require('egg').Subscription;
class UpdateArticleStatus extends Subscription {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
static get schedule() {
return {
interval: '2s', // 1 分钟间隔
type: 'all', // 指定所有的 worker 都需要执行
};
}
* subscribe(ctx) {
const res = yield ctx.service.article.getAllArticles(1);
console.log(res);
}
}
module.exports = UpdateArticleStatus;
运行提示:
excute error. Cannot read property 'service' of undefined
我照官网的例子:
module.exports = {
schedule: {
interval: '1m', // 1 分钟间隔
type: 'all', // 指定所有的 worker 都需要执行
},
* task(ctx) {
const res = yield ctx.curl('http://www.api.com/cache', {
dataType: 'json',
});
ctx.app.cache = res.data;
},
};
发现curl属性也是不能访问
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它已经提示你了,
Cannot read property 'service' of undefined
说明 service 属性前面的
ctx
是 undefined。你这属于混着写,不遵守他示例的格式。
第一个写法里面,subscribe 函数是没有 ctx 这个参数的。
第二个属于简写写法,ctx.curl 是可以访问的啊,你可以在 task 函数里直接
是可以访问到函数原型的,没有明白你这个 curl 无法访问的意思。
创建匿名ctx
const ctx = app.createAnonymousContext()
缺了this
用this.ctx
而且要记得在头部引用
const Subscription = require('egg').Subscription;
另外egg2.0已经支持await如果升级到2.0,可以用await