鍍金池/ 問(wèn)答/HTML/ eggjs 在定時(shí)器訪問(wèn)service提示Cannot read propert

eggjs 在定時(shí)器訪問(wèn)service提示Cannot read property 'service' of undefined

update_article.js(schedule目錄下):

const Subscription = require('egg').Subscription;

class UpdateArticleStatus extends Subscription {
    // 通過(guò) schedule 屬性來(lái)設(shè)置定時(shí)任務(wù)的執(zhí)行間隔等配置
    static get schedule() {
        return {
            interval: '2s', // 1 分鐘間隔
            type: 'all', // 指定所有的 worker 都需要執(zhí)行
        };
    }

    * subscribe(ctx) {
        const res = yield ctx.service.article.getAllArticles(1);
        console.log(res);
    }
}
module.exports = UpdateArticleStatus;

運(yùn)行提示:
excute error. Cannot read property 'service' of undefined

我照官網(wǎng)的例子:

module.exports = {
  schedule: {
    interval: '1m', // 1 分鐘間隔
    type: 'all', // 指定所有的 worker 都需要執(zhí)行
  },
  * task(ctx) {
    const res = yield ctx.curl('http://www.api.com/cache', {
      dataType: 'json',
    });
    ctx.app.cache = res.data;
  },
};

發(fā)現(xiàn)curl屬性也是不能訪問(wèn)

回答
編輯回答
刮刮樂(lè)

創(chuàng)建匿名ctx
const ctx = app.createAnonymousContext()

2017年12月11日 19:59
編輯回答
我以為

它已經(jīng)提示你了, Cannot read property 'service' of undefined
說(shuō)明 service 屬性前面的 ctx 是 undefined。

你這屬于混著寫(xiě),不遵守他示例的格式。

第一個(gè)寫(xiě)法里面,subscribe 函數(shù)是沒(méi)有 ctx 這個(gè)參數(shù)的。

第二個(gè)屬于簡(jiǎn)寫(xiě)寫(xiě)法,ctx.curl 是可以訪問(wèn)的啊,你可以在 task 函數(shù)里直接

console.log(ctx.curl.toString());

是可以訪問(wèn)到函數(shù)原型的,沒(méi)有明白你這個(gè) curl 無(wú)法訪問(wèn)的意思。

2017年8月13日 18:19
編輯回答
假灑脫

缺了this

用this.ctx

而且要記得在頭部引用 const Subscription = require('egg').Subscription;

另外egg2.0已經(jīng)支持await如果升級(jí)到2.0,可以用await

2018年2月25日 08:23