使用异步库进行环回时会遇到串行回调问题,同时将一个结果回调发送给另一个

时间:2019-05-26 08:39:07

标签: node.js strongloop loopback async.js

我正在使用后端API的环回,这里用于从MySQL提取数据,这里是在对它执行操作的同时,我正在使用async npm库,

执行块级功能执行,同时面对这些遇到挫折并带有autocallBack功能问题的情况。

Unhandled rejection TypeError: autoCallback is not a function

这是我的伪代码。

ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return cb({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (autoCallback, result) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };

获取==> autoResult的对象函数中的err是未定义的。

该问题的任何解决方案,请发送。

谢谢。

1 个答案:

答案 0 :(得分:0)

这是解决方案,我只是更改了函数参数,它对我有用!

ModalName.remoteMethod = function (data, cb) {
    async.auto({
      firstCallingFunction: function (autoCallback) {
        ModalName.find({
          id: 1
        }, yourResult => {
            if (err) {
                return autoCallback({
                success: false,
                msg: 'Insufficient parameters',
                data: err,
                });
            } else {
                return autoCallback(null, yourResult);
            }
            });
        },
        secondCallingFunction: ['firstCallingFunction', function (result, autoCallback) {
            console.log('result=====>', result)
            ModalName.find({id: result['id']})
            .then(function(dbResult) {
            if (dbResult) {
                console.log('dbResult==========>', dbResult.toJSON());
                return autoCallback(null, dbResult);
            }
            });
        }],
    }, function (error, autoResult) {
      if (error) {
        return cb(null, error);
      } else {
        return cb(null, {
          success: true,
          msg: 'result fetched',
          data: autoResult.secondCallingFunction,
        });
      }
    });
  };