How to solve the problem of Promise { <pending> }?

Here is my code:

Blockquote

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
  });
});

When I run the code I get this output:

Blockquote

   [ { 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> } } ]

I don’t know how to solve it

You can try this:

url: url.then(function(result) {
    return result;
     })

Seems weird to me, but since you return nothing from the anonymous function url result as a pending Promise i guess^^

function(result) {
        result;
}

Will be call in another stack, it just a callback which will execute in the future.
And .then will return a promise as designed.

Something like this happen when you call
url.then(callback)

  • url is a promise, .then use to register callback to event loop. => "if you done that, execute the callback".
  • ok! Now you (then) end your job. Return another promise.

With .then or async await.

Looks like you are not waiting for your promises to be settled. Try that:

let data = await Promise.all(q.map(async 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: await url
    };
  }));

You are using Promise.all ? Are you have multiply promises ?

q is an array and since there’s asynchronous code being executed inside each values’ callback you should wait till all of them finish.