Javascript 我可以只使用一个打印获取API数据吗?
像这样Javascript 我可以只使用一个打印获取API数据吗?,javascript,jquery,Javascript,Jquery,像这样 fetch(signup_url, { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: user_name.value, email: usr_email.value,
fetch(signup_url, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: user_name.value,
email: usr_email.value,
password: usr_password.value,
username: user_name.value,
lastname: usr_last_name.value,
type: usr_type.value,
phone: ph_number.value
})
})
.then((res) => {
var data = res.json() //Promise
console.log(data)
})
您只需等待异步函数:
fetch(signup_url, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: user_name.value,
email: usr_email.value,
password: usr_password.value,
username: user_name.value,
lastname: usr_last_name.value,
type: usr_type.value,
phone: ph_number.value
})
})
.then(async (res) => {
var data = await res.json()
console.log(data)
})
尽管我不明白你为什么只想使用1。你的bug到底是什么,你的代码在哪里?任何一个链都承诺如下:
fetch(…).then(res=>res.json()).then(data=>console.log(data))
或使用异步/await
:让res=await-fetch(…);让data=wait res.json();控制台日志(数据)
@ibrahimmahrir仅使用await
肯定比混合使用Promise样式和await样式更干净,因为您可以将注释更改为//resolved Promise
,因为它正在等待。或者将其删除XDThank you@Elanochecer