Array.push不是Promise内部的函数 [关闭] 。

问题描述 投票:1回答:2

在下面的代码块中遇到了这个错误。你可以看到我实例化了 report = [] 里面 async 函数,但在我运行一个 async Promise.all. 在这个承诺的内部,我运行一些处理程序,这些处理程序应该获取数据,并将其推送回至 report 数组,该数组的作用域在承诺之外。我试着把它改成 letconst 以及把 Promise.all 变成 try/catch 块,但总是得到同样的错误......

完整的错误。

TypeError: report.push(...) is not a function
(node:2568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

代码:

(async (env) => {
  const report        = []
  const subscriptions = await xm.subscriptions.getMany(env);

  await Promise.all(subscriptions.map(sub => {
    let apps_and_lobs = xm.subscriptions.process_apps_and_lobs(sub.criteria.data);
    let sub_obj = {
      sub_name         : sub.name,
      sub_uuid         : sub.id,
      form_name        : sub.form.name,
      form_id          : sub.form.id,
      plan_name        : sub.form.plan.name,
      plan_id          : sub.form.plan.id,
      owner_targetName : sub.owner.targetName,
      owner_firstName  : sub.owner.firstName,
      owner_lastName   : sub.owner.lastName,
      applications     : apps_and_lobs.apps,
      lob              : apps_and_lobs.lobs
    }

    report.push(sub_obj) // <----- ***** This is failing ******

    (async (env) => {
      let recipients = await xm.subscriptions.getSubscribers(env, null, sub.id);
      recipients.map(r => {
        util.cmt(JSON.stringify(r, null, 2));
      })
    })(env)
  }))
})(prod);
javascript arrays asynchronous promise scoping
2个回答
2
投票

正如Andreas所指出的,那是一个分号。我想总是检查你的分号吧......


1
投票

使用 array.save() 作为 report.save() 以保存对象本身。

(async (env) => {
  const report        = []
  const subscriptions = await xm.subscriptions.getMany(env);

  await Promise.all(subscriptions.map(sub => {
    let apps_and_lobs = xm.subscriptions.process_apps_and_lobs(sub.criteria.data);
    let sub_obj = {
      sub_name         : sub.name,
      sub_uuid         : sub.id,
      form_name        : sub.form.name,
      form_id          : sub.form.id,
      plan_name        : sub.form.plan.name,
      plan_id          : sub.form.plan.id,
      owner_targetName : sub.owner.targetName,
      owner_firstName  : sub.owner.firstName,
      owner_lastName   : sub.owner.lastName,
      applications     : apps_and_lobs.apps,
      lob              : apps_and_lobs.lobs
    }

    report.push(sub_obj) // <----- ***** This is failing ******
    report.save();

    (async (env) => {
      let recipients = await xm.subscriptions.getSubscribers(env, null, sub.id);
      recipients.map(r => {
        util.cmt(JSON.stringify(r, null, 2));
      })
    })(env)
  }))
})(prod);
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.