App.js
/**
* async & await
*
*/
// async function myFunc(){
// // return "Hello World!";
// const promise = new Promise((resolve,reject) => {
// setTimeout(() => resolve('Hello World!'),2000)
// })
// // 錯(cuò)誤信息
// const error = true;
// if(!error){
// // 等待resolve執(zhí)行完畢之后,才會(huì)執(zhí)行
// const res = await promise;
// return res;
// }else{
// await Promise.reject(new Error("error: 報(bào)錯(cuò)了!"));
// }
// }
// // console.log(myFunc());
// myFunc()
// .then(data => console.log(data))
// .catch(err => console.log(err));
// 請(qǐng)求數(shù)據(jù)
async function getUsers(){
const response = await fetch("http://jsonplaceholder.typicode.com/users");
const data = await response.json();
return data;
}
getUsers().then(users => console.log(users))
esay HTTP.JS
/**
* 封裝fetch
* 更快,更簡(jiǎn)單的請(qǐng)求數(shù)據(jù)
*
* @version 1.0.0
* @author 米斯特吳
* @license MIT
*
**/
class EasyHttp{
// get
get(url){
return new Promise((resolve,reject) => {
fetch(url)
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// post
post(url,data){
return new Promise((resolve,reject) => {
fetch(url,{
method:"POST",
headers:{
'Content-type':'application/json'
},
body:JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// put
put(url,data){
return new Promise((resolve,reject) => {
fetch(url,{
method:"PUT",
headers:{
'Content-type':'application/json'
},
body:JSON.stringify(data)
})
.then(res => res.json())
.then(data => resolve(data))
.catch(err => reject(err))
})
}
// delete
delete(url){
return new Promise((resolve,reject) => {
fetch(url,{
method:"DELETE",
headers:{
'Content-type':'application/json'
}
})
.then(res => res.json())
.then(data => resolve('數(shù)據(jù)刪除成功!'))
.catch(err => reject(err))
})
}
}