为啥直接使用 await filterPool(data) 会报错

为啥直接使用 await filterPool(data) 会报错

async function filterPool(data){
    const objectRes = await api 
    return objectRes
}

function handleGetLocalRegionList() {
    severApi(params).then((res) => {
        const data = res.results || []
        const Pool = await filterPool(data)
    })
}

因为:await 只能在 async 函数内部 或 模块顶层 使用。
你的 handleGetLocalRegionList 是一个普通函数,不是 async,所以里面用 await 会报错。
总结:await 必须写在 async 函数体内,只看它所在的那一层函数,不看外层。

解决办法

async function filterPool(data){
    const objectRes = await api 
    return objectRes
}

async function handleGetLocalRegionList() {
    // 因为:await 只能在 async 函数内部 或 模块顶层 使用。
    severApi(params).then(async (res) => {
        const data = res.results || []
        const Pool = await filterPool(data)
    })
}

// 解决办法2:async写在then函数中
function handleGetLocalRegionList() {
    severApi(params).then(async (res) => {
        const data = res.results || []
        const Pool = await filterPool(data)
    })
}
posted @ 2026-10-08 13:45  南风晚来晚相识  阅读(3)  评论(0)    收藏  举报