【问题标题】:Can't get data from fetch无法从 fetch 中获取数据
【发布时间】:2020-01-24 19:49:52
【问题描述】:

我正在尝试进行 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()

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

【问题讨论】:

  • fetch_output 不返回任何内容 -> const fetch_output = (data) => fetch(...)
  • 试试这个 fetch_output = (data) => await ... 而不是 fetch_output = (data) => {...}) 。更好地阅读ES6 Arrow behaviour
  • @AngelQuesada 它没有。安德烈亚斯是正确的。
  • @prasanth 你不需要async/await fetch_output
  • @Andreas 是正确的。我只是用箭头替换括号

标签: javascript asynchronous async-await fetch


【解决方案1】:

这是因为异步函数返回一个promise,该promise解析为函数返回的值

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

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

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

【讨论】:

    【解决方案2】:

    因为您调用了await fetch_output(),所以您不应该使用.then() 来检索其结果。删除await

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

    【讨论】:

    • 这根本不是真的...async/await 只是Promises 和.then() 周围的语法糖。你可以完全混合它们:jsfiddle.net/wkuqc6xm
    猜你喜欢
    • 1970-01-01
    • 2020-11-16
    • 2017-02-18
    • 1970-01-01
    • 2018-07-20
    • 2019-07-20
    • 2019-09-11
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多