如何解决Promise {<pending>}问题?

时间:2018-10-09 15:10:51

标签: node.js koa2

这是我的代码:

router.get("test", async ctx => {
  let q = await ctx.db
    .execute(`SELECT w.create_time as create_time,w.camera_id,w.status,
  w.problem_type_id,w.repair_user_id,w.no as no,wp.pic_url
  FROM work_flow w
  left OUTER
  JOIN work_flow_pic wp ON w.no=wp.flow_id`);
  let data = q.map(item => {
    let url = ctx.db.execute(
      `select * from work_flow_pic where flow_id=${item.no}`
    );
    return {
      create_time: item.create_time,
      no: item.no,
      url: url.then(function(result) {
        result;
      })
    };
  });
  console.log(data);
  let retstr = `[{"ret":"0"}]`;
  await ctx.render("interface_ret", {
    retstr
  });
});

运行代码时,我得到以下输出:

    [ { create_time: 2018-10-09T02:47:54.000Z,
    no: '153905327352986',
    url: Promise { <pending> } },
  { create_time: 2018-10-09T02:47:54.000Z,
    no: '153905327352986',
    url: Promise { <pending> } },
  { create_time: 2018-10-09T08:51:33.000Z,
    no: '153905327352987',
    url: Promise { <pending> } } ]

我不知道如何解决

3 个答案:

答案 0 :(得分:1)

当您要等待一个承诺得到解决并获得其返回值时,可以像上面一样使用await

let q = await ctx.db.execute(`SELECT w.create_time as 
     create_time,w.camera_id,w.status,
     w.problem_type_id,w.repair_user_id,w.no as no,wp.pic_url
     FROM work_flow w left OUTER JOIN work_flow_pic wp ON w.no=wp.flow_id`);//get q from table
let data = q.map(item => {
let url = await ctx.db.execute(`select * from work_flow_pic where 
flow_id=${item.no}`); //get url from q
return {
  create_time: item.create_time,
  no: item.no,
  url: url
  })
}
});
  console.log(data);

答案 1 :(得分:0)

enter image description here

我终于弄清楚了这个问题。

答案 2 :(得分:0)

let ps = q.map(async item => {
  let url = await ctx.db.execute(
    `select * from work_flow_pic where flow_id=${item.no}`
  );
  return {
    create_time: item.create_time,
    no: item.no,
    url: url
  };
});

const data = await Promise.all(ps);

使用地图制作promise数组,等待所有完成=>所有数据(array)