调用.then语法后Promise仍显示pending状态的问题求助
问题分析与解决
核心问题
你的代码里有三个关键问题导致resolved显示为pending状态的Promise:
同步代码优先执行
console.log(resolved)是同步运行的,而getTrades()是异步操作,此时Promise还没完成状态变更,所以打印出来的自然是pending状态的Promise对象。getTrades函数无返回值
你在getTrades里用了await getTradesInfo(...),但没有把这个调用的结果返回出去,所以这个async函数默认返回的是一个resolved状态的undefined的Promise,后续链式调用也拿不到有效结果。Promise链式调用仍返回Promise
不管你加多少个.then(),then方法本身都会返回一个新的Promise,永远不会直接变成同步的最终值,必须在异步回调或者await之后才能拿到结果。
修复后的代码
第一步:修复getTrades,让它返回结果
const getTrades = async () => { // 先处理找不到账户的边界情况,避免报错 const targetAccount = accounts?.find(account => account.type === 'EXCHANGE'); if (!targetAccount) return null; const accountId = targetAccount.id; // 返回getTradesInfo的执行结果 return await getTradesInfo({ accountId: accountId }); };
第二步:正确获取异步结果
有两种常用方式:
方式一:用async/await
// 包裹在async函数里执行 const fetchAndLogTrades = async () => { const resolved = await getTrades(); console.log(resolved); // 这里能拿到最终的resolved结果 }; fetchAndLogTrades();
方式二:用.then()回调
getTrades().then(resolved => { console.log(resolved); // 这里能拿到最终的resolved结果 });
内容的提问来源于stack exchange,提问作者Kimbo
相关产品推荐
相关产品推荐

