You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Async-Await返回Promise{<Pending>} 无法获取实际值数组如何解决

问题原因

  • 调用Array.map传入async函数时,每次迭代返回值都是Promise对象,因此你得到的resultArray本身就是Promise数组,属于正常表现。
  • 原代码中console.log(Promise.all(resultArray).then((r)=> console.log(r)))打印的是Promise.all的返回值,它本身是Promise实例,因此会输出Promise { <pending> }。
  • 异步操作的结果只能在Promise状态变为已完成后获取,无法直接在同步执行的代码中直接拿到异步返回值。

解决方案

方案1:在then回调中处理结果

所有对结果数组的操作都放在Promise.all的then回调中即可:

let object = [
    "hello1",
    "hello2",
    "hello3",
    "hello4"
]

async function funct(value){
    return new Promise((res,rej)=> res( value + '-world'));
}

let resultArray = object.map(async (e)=>{
    let result = await funct(e);
    return result
})

Promise.all(resultArray).then((r)=> {
    // r就是你需要的实际结果数组
    console.log(r)
    // 后续对结果的处理逻辑都写在这里
})

输出结果:

[ 'hello1-world', 'hello2-world', 'hello3-world', 'hello4-world' ]

方案2:用await获取结果(避免回调嵌套)

如果不想写回调嵌套,可以将逻辑包裹在async自执行函数中,用await等待Promise.all执行完成拿到结果:

let object = [
    "hello1",
    "hello2",
    "hello3",
    "hello4"
]

async function funct(value){
    return new Promise((res,rej)=> res( value + '-world'));
}

// async自执行函数
(async () => {
    let resultArray = object.map(async (e)=> await funct(e))
    // 等待所有Promise执行完成,直接拿到结果数组
    const finalResult = await Promise.all(resultArray)
    console.log(finalResult)
    // 后续处理逻辑可以直接使用finalResult
})()

如果你的运行环境支持ES模块+顶层await(比如Node.js 14.8+、现代浏览器),也可以直接在顶层作用域写await Promise.all(resultArray),不需要额外包裹函数。


内容的提问来源于stack exchange,提问作者monk_7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 10:15:04