<!--
* @Author: RealRoad1083425287@qq.com
* @Date: 2023-03-20 14:36:48
* @LastEditors: Mei
* @LastEditTime: 2023-03-20 14:42:27
* @FilePath: \vscode\promise.html
* @Description:
*
* Copyright (c) 2023 by ${git_name_email}, All Rights Reserved.
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var q=new Promise(function(resolve,reject){
setTimeout(() => {
resolve(["1","2","3"])//同意承诺
//reject() 拒绝承诺
}, 2000);
})
q.then(function(res){
console.log("success",res)
}).catch(function(){
console.log("fail")
})
</script>
</body>
</html>
fetch(默认get方式)
var username="xiaohong"
fetch(`http://localhost:3000/users?username=${username}`).then(res=>{
console.log(res)//res.json() Promise对象
if(res.ok){
return res.json() }
else{
return Promise.reject({
a:1,
status:res.status,
statusText:res.statusText
})
} //只有一个对象时,可以省略大括号和return
}).then(res=>{
console.log(res)
})
post方式
fetch("http://localhost:3000/users",{
method:"POST",
headers:{
"content-type":"application/x-www-form-urlencoded"
},
body:"username=xiaohua&password=111"
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
json格式
fetch("http://localhost:3000/users",{
method:"POST",
headers:{
"content-type":"application/json"
},
body:JSON.stringify({
username:"mez",
password:"478"})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
Put方式
fetch("http://localhost:3000/users/2",{
method:"PUT",
headers:{
"content-type":"application/json"
},
body:JSON.stringify({
username:"mez",
password:"478"})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
PATCH方式
fetch("http://localhost:3000/users/3",{
method:"PATCH",
headers:{
"content-type":"application/json"
},
body:JSON.stringify({
username:"mez",
password:"478"})
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})
delete方式
fetch("http://localhost:3000/users/3",{
method:"delete"
})
.then(res=>res.json())
.then(res=>{
console.log(res)
})

本文演示了如何使用Promise处理异步操作,特别是在fetchAPI中的应用。示例包括GET请求、POST请求以及其他HTTP方法(PUT、PATCH和DELETE),并强调了内容类型在发送JSON数据时的重要性。
3598

被折叠的 条评论
为什么被折叠?



