nodejs async库使用错误: cannot read property 'xxx' of undefined

来源:互联网 发布:酷讯dt35淘宝可靠吗 编辑:程序博客网 时间:2024/06/05 08:20

nodejs是执行在服务器端的异步javascript,所以异步执行是nodejs的最大特点。大多数时候,我们需要异步执行来获取更高的吞吐率,提高程序的效率。
然而,当我们需要让某些函数按照一定的顺序执行时,就需要用到async库中的series()函数了。

函数体

var async = require(‘async’) async.series(function(cb) {        step1(function(err, v1) {                // do something with v1                cb(err, v1);        }),        function(cb) {                step2(...)        },        function(cb) {                step3(...)        });

上面的函数体中,一共顺序执行三个函数。
然而当我在写如下代码的时候,程序报错:

async.series(        dishesCtrlr.getDishes(start,count,function(errer,result){        if(result && result.length>=0)        {            res.send(result);        }        else        {            console.log("------insert errer----------");        }    }));

错误:

  • Cannot read property ‘series’ of undefined
  • Cannot read property ‘constructor’ of undefined

于是搜索之后找到答案:

In general, without code it is really hard to find issue, just copy your ‘options on the fly’ which reproduce issue, please.
However, most probably you are trying to add series for axis, which doesn’t exists. For example:

yAxis: { },
series: [{ yAxis: 1 }] <-- obviously there is only one yAxis

也就是说,如果要用series顺序执行一些函数的话,async.series(),括号中的函数个数必须大于1.
于是修改我的代码如下,无错:

async.series(function (){        start=(req.param.curPage-1)*count;        console.log(start);    },    dishesCtrlr.getDishes(start,count,function(errer,result){        if(result && result.length>=0)        {            res.send(result);        }        else        {            console.log("----insert errer----------");        }    }));

另外,async不仅有流水执行函数series,还有并行,以及其他。详见:nodejs中Async库介绍
其他参考:XXX cannot read property ‘series’ of undefined

0 0
原创粉丝点击