仅当我返回单个值时异步远离解析承诺

问题描述 投票:0回答:1

我使用异步/等待进行以下获取:

async function postData(url = "", data = {}) {
    // Default options are marked with *
    const response = await fetch(url, {
        method: "POST", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, *cors, same-origin
        credentials: "include",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    });
    //return response.json(); // parses JSON response into native JavaScript objects
    return {status:response.status, message:response.json()};
}

如果我只使用带注释的返回值,我会正确获取 API 返回的 JSON,如果我使用第二个返回值,response.json 最终会是一个

承诺:{“待定”}

如何从函数中获取这两个信息? API 向我发送如下数据:

return res.status(200).json("Message to be displayed");
async-await fetch-api
1个回答
0
投票

json()
方法也是
async
,你需要
await
它:

return { status: response.status, message: await response.json() };
© www.soinside.com 2019 - 2024. All rights reserved.