函数内部console.log能获取异步结果,但调用时返回Promise对象的问题求助
为什么getTrades函数返回的不是预期布尔值,而是Promise?
问题代码
const getTrades = () => { const accountId = accounts.find(account => account.type === 'INTERNAL').id; const response = showTrades({ accountId: accountId }).then(res => console.log(res)) if (response.length === 0) return false; return true; };
问题原因
response是Promise对象,不是异步结果:showTrades()返回Promise,调用.then()后依然返回新的Promise,所以response存储的是Promise,而非你期望的数组。- 同步代码无法获取异步结果:函数里的
if (response.length === 0)是同步执行的,此时showTrades的异步操作还未完成,Promise没有length属性,response.length等于undefined,因此条件不成立,函数直接返回true。而你看到的console.log(res)输出空数组,是在异步回调中执行的,此时函数早就已经返回了结果。 - 你提到调用
getTrades()返回Promise,大概率是混淆了response变量和函数返回值——原函数本身是同步函数,返回的是布尔值,但如果后续错误地将其当作Promise处理,或者实际代码中误将getTrades声明为async函数,才会出现这种情况。
解决方法
要正确处理异步操作的结果,必须将函数改为异步模式,以下两种方案任选:
方案一:使用async/await(更直观)
const getTrades = async () => { const accountId = accounts.find(account => account.type === 'INTERNAL').id; const res = await showTrades({ accountId: accountId }); console.log(res); // 数组为空返回false,否则返回true return res.length !== 0; };
调用方式:
// 用.then()处理结果 getTrades().then(result => { console.log(result); // 这里拿到预期的布尔值 }); // 或在async函数内用await调用 async function handleTrades() { const result = await getTrades(); console.log(result); } handleTrades();
方案二:直接返回Promise
const getTrades = () => { const accountId = accounts.find(account => account.type === 'INTERNAL').id; return showTrades({ accountId: accountId }).then(res => { console.log(res); return res.length !== 0; }); };
调用方式和方案一一致,通过.then()或await获取布尔结果。
内容的提问来源于stack exchange,提问作者Kimbo
相关产品推荐
相关产品推荐

