在async.parallel中异步等待,回调变得未定义

时间:2018-05-04 14:45:02

标签: javascript node.js asynchronous

我正在尝试在async.parallel中执行异步/等待,但无法调用回调。但是如果我删除async / await,则可以调用回调。以下是代码

<div>

有人可以指出代码有什么问题吗?

2 个答案:

答案 0 :(得分:3)

不要将async.js库用于承诺代码,也不要使用回调参数。只需使用Promise.all等待多项内容:

let promises = listCamId.map(async function(camId) {
  let insertRuleTransParam = {
    rule_id: ruleId,
    camera_id: camId,
    vas_id: vasId,
    additional_parameter: additionalParameter
  }

  let configParamCamera = { where: { id: camId } };
  let configParamRule = { where: { id: ruleId } };

  let ruleTrans = await createRuleTransaction(insertRuleTransParam);
  let rule = await ruleService.find(configParamRule, "one");
  let cam = await cameraService.find(configParamCamera, "one");
  let uri = await constructCamUri(cam.protocol, cam.user_access, cam.password, cam.ip_address, cam.port, cam.path);
  let visionParam = await startVasRule(vasId, ruleTrans.id, camId, rule.rule_path, rule.rule_exec, uri);
  let updateRuleParam = {
    port_stream: visionParam.port,
    url_stream: visionParam.url,
    mmap_in: visionParam.mmap_in,
    mmap_out: visionParam.mmap_out
  }
  await updateRuleTransaction(updateRuleParam);
  return null;
});
return Promise.all(promises);

答案 1 :(得分:0)

您可以在async.js中使用async / await

您的代码中存在一个主要错误:

return async function (callback) {}

异步功能不需要或不需要callback,它们是Promises的简写

这是一个async function的简单示例,它将在async.js中工作:

async function forAsync() {
  try {
    let user = await db.findOne({});
    return user // this is equivalent to resolve(user)
  } catch (e) {
    throw(e) // this is equivalent to reject(err)
  }
}

作为Promise,如下所示:

function forAsync() {
  return new Promise((resolve,reject) => {
    db.findOne({}, (err,res) => {
      if (err) reject(err)
      let user = res;
      resolve(user);
    });
  }
}

作为callback,如下所示:

function forAsync(callback) {
  db.findOne({}, (err,res) => {
    if (err) callback(err)     
    let user = res;     
    callback(null, user);
  });
}