无法从提取中获取数据

时间:2020-01-24 11:28:36

标签: javascript asynchronous async-await fetch

我正在尝试进行访存调用,并且可以正常工作,但是当我尝试从另一个函数获取结果时,我总是会不确定。

这是我的代码:

const fetch_output = async (data) => {
await fetch("execute_command", {
    method: "POST",
    credentials: "same-origin",
    headers: {
        "X-CSRFToken": getCookie("csrftoken"),
        "Accept": "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(data)
}).then(function(response) {
    return response.json()
}).then(function(response) {
    console.log(response)
    //I get the correct response here
    return response
}).catch(function(ex) {
    console.log("Ha habido algún error: ", ex)
})
}

const write_outputs = async () => {
for (const platform_id of platforms_ids) {

    const data = {
        platform_id:platform_id,
        command:command
    }

    await fetch_output(data).then((resp)=>{
        console.log(resp)
        //I get undefined
    })
}
}

write_outputs()

我已经尝试了一切,但我只是不知道我在做什么错。

2 个答案:

答案 0 :(得分:1)

这是因为异步函数返回的承诺会解析为该函数的返回值

(async () => {})().then(value => console.log("value = ", value)); // undefined
(async () => {return 1})().then(value => console.log("value =" , value)); // 1

由于您未从fetch_output返回任何内容,因此解析为未定义

您应该从fetch_output函数返回,而不要使用await。 另外,由于获取已经是一个承诺,因此您可以使用普通函数代替异步函数

答案 1 :(得分:0)

由于调用await fetch_output(),因此不应使用.then()来检索其结果。放下await

为什么? await以其处理Promise或异步功能的方式将function().then().catch()替换为result = await function()。使用await.then(),但不能同时使用。