【发布时间】: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/awaitfetch_output -
@Andreas 是正确的。我只是用箭头替换括号
标签: javascript asynchronous async-await fetch