尽管调用了 .then 语法并解析了它 [duplicate],但仍然持续显示挂起的 promise 对象

Continuously showing a pending promise object despite calling the .then syntax and resolving it [duplicate]

提问人:Kimbo 提问时间:11/23/2022 最后编辑:E_net4Kimbo 更新时间:11/23/2022 访问量:40

问:

我只是想在试图解决承诺时找出这里到底发生了什么。就像我下面的代码一样,我一直在尝试照顾和解决承诺,但即使在到处寻找答案之后,在这一点上也只是一种痛苦。

const getTrades = async () => {
    const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;

    await getTradesInfo({ accountId: quadAccountId });
  };

  const pending = getTrades().then(res => { return res });

  const resolved = pending.then(res => { return res });

  console.log(resolved);

因此,出于某种原因,上面解析的变量仍然显示一个待处理的对象。

javascript jquery reactjs 异步 承诺

评论

1赞 Tim Klein 11/23/2022
您的函数中缺少关键字?returngetTrades
0赞 Pipe 11/23/2022
要从“then”返回值...您需要使用 await...否则你会得到承诺
0赞 Rohit Khanna 11/23/2022
我可以通过这段代码得到的是:返回一个 promise 对象。如果真的想用,最好用thenpendingconst pending = await getTrades().then(res => { return res });
0赞 Bergi 11/23/2022
then不返回回调的结果 - 它不能,回调稍后调用!- 但它返回了对结果的承诺。

答:

0赞 Martinez 11/23/2022 #1

您的代码仍然是异步的,您的控制台日志不会等待您的承诺被执行。

这里有一个可能的解决方案:

const getTrades = async () => {
    const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;

   return getTradesInfo({ accountId: quadAccountId });
  };

  getTrades.then((res)=> <here can use your console.log> )

或者用 async/await 包装它:

const getTrades = async () => {
  const accountId = accounts && accounts.find(account => account.type === 'EXCHANGE').id;

 return getTradesInfo({ accountId: quadAccountId });
};
(async ()=> {
  const result  = await getTrades();

  console.log(result)
})()