语法
2024年04月17日
一、GET
function normalizeUrl(url, params) {
let queryString = Object.keys(params).reduce((prev, key) => {
return (prev += `${key}=${params[key]}&`);
}, "?");
return url + queryString.slice(0, queryString.length - 1);
}
function get(url,params){
const normalizedUrl = normalizeUrl(url,params);
return fetch(normalizedUrl, {
method: "GET",
}).then(res=>{
console.log(res);
if(res.ok){
return res.json();
}
return Promise.reject(res.statusText);
}).catch(error=>{
return Promise.reject(error);
});
}
get("http://test.bolawen.com/server/sync",{a:1,b:2}).then(res=>{
console.log(res);
});
二、POST
function post(url, params) {
return fetch(url, {
method: "POST",
body: JSON.stringify(params || {})
})
.then((res) => {
console.log(res);
if (res.ok) {
return res.json();
}
return Promise.reject(res.statusText);
})
.catch((error) => {
return Promise.reject(error);
});
}
post("http://test.bolawen.com/server/sync", { a: 1, b: 2 }).then((res) => {
console.log(res);
});
三、Abort
function normalizeUrl(url, params) {
let queryString = Object.keys(params).reduce((prev, key) => {
return (prev += `${key}=${params[key]}&`);
}, "?");
return url + queryString.slice(0, queryString.length - 1);
}
function request(url, method, params, header, signal) {
const normalizeMethod = method.toUpperCase();
const normalizedUrl =
normalizeMethod === "GET" ? normalizeUrl(url, params) : url;
const normalizedOptions = {
method,
signal: signal,
body: normalizeMethod === "GET" ? null : JSON.stringify(params),
};
return fetch(normalizedUrl, {
method: normalizeMethod,
...normalizedOptions,
})
.then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.statusText);
})
.catch((error) => {
if(typeof error === 'object'){
return Promise.reject(`错误类型为: ${error.name}, 具体原因: ${error}`);
}
return Promise.reject(error);
});
}
const controller = new AbortController();
const signal = controller.signal;
request("http://test.bolawen.com/server/async",'post',{a:1,b:2},null,signal).catch(error=>{
console.log(error)
});
setTimeout(()=>{
controller.abort();
},3000);
四、Timeout Abort
4.1 Promise.race
function normalizeUrl(url, params) {
let queryString = Object.keys(params).reduce((prev, key) => {
return (prev += `${key}=${params[key]}&`);
}, "?");
return url + queryString.slice(0, queryString.length - 1);
}
function baseRequest(url, method, params, header, signal) {
const normalizeMethod = method.toUpperCase();
const normalizedUrl =
normalizeMethod === "GET" ? normalizeUrl(url, params) : url;
const normalizedOptions = {
method,
body: normalizeMethod === "GET" ? null : JSON.stringify(params),
};
return fetch(normalizedUrl, {
method: normalizeMethod,
...normalizedOptions,
})
.then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.statusText);
})
.catch((error) => {
if (typeof error === "object") {
return Promise.reject(`错误类型为: ${error.name}, 具体原因: ${error}`);
}
return Promise.reject(error);
});
}
function timeoutAbort(timeout){
return new Promise((resolve,reject)=>{
setTimeout(() => {
reject('abort');
}, timeout);
});
}
function request(){
return baseRequest(
"http://test.bolawen.com/server/async",
"post",
{ a: 1, b: 2 },
null
);
}
Promise.race([
timeoutAbort(4000),
request()
]).then(res=>{
console.log(res);
}).catch((error)=>{
console.log(error)
});
4.2 AbortSignal.timeout
function normalizeUrl(url, params) {
let queryString = Object.keys(params).reduce((prev, key) => {
return (prev += `${key}=${params[key]}&`);
}, "?");
return url + queryString.slice(0, queryString.length - 1);
}
function request(url, method, params, header, signal) {
const normalizeMethod = method.toUpperCase();
const normalizedUrl =
normalizeMethod === "GET" ? normalizeUrl(url, params) : url;
const normalizedOptions = {
method,
signal: signal,
body: normalizeMethod === "GET" ? null : JSON.stringify(params),
};
return fetch(normalizedUrl, {
method: normalizeMethod,
...normalizedOptions,
})
.then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.statusText);
})
.catch((error) => {
if (typeof error === "object") {
return Promise.reject(`错误类型为: ${error.name}, 具体原因: ${error}`);
}
return Promise.reject(error);
});
}
const signal = AbortSignal.timeout(3000);
request(
"http://test.bolawen.com/server/async",
"post",
{ a: 1, b: 2 },
null,
signal
)
.then((res) => {
console.log(res);
})
.catch((error) => {
console.log(error);
});
补充服务
Koa Server
const Koa = require("koa");
const KoaRouter = require("koa-router");
const app = new Koa();
const router = new KoaRouter({ prefix: "/" });
function wait(time) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
router.get("sync", async (ctx) => {
ctx.body = {
code: 200,
msg: "get 同步请求成功!",
};
});
router.get("async", async (ctx) => {
await wait(8000);
ctx.body = {
code: 200,
msg: "get 异步请求成功!",
};
});
router.post("sync", async (ctx) => {
ctx.body = {
code: 200,
msg: "post 同步请求成功!",
};
});
router.post("async", async (ctx) => {
await wait(8000);
ctx.body = {
code: 200,
msg: "post 异步请求成功!",
};
});
app.use(router.routes());
app.listen("4000", () => {
console.log("服务启动成功!");
});