promise封装常用方法
2020-08-10 本文已影响0人
若年
整理自后盾人网站
1.timeout方法
function timeout(delay = 1000) {
return new Promise(resolve => setTimeout(resolve, delay));
}
timeout(2000)
.then(() => {
console.log("houdunren.com");
return timeout(2000);
})
.then(value => {
console.log("hdcms.com");
});
2.interval方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>后盾人</title>
<style>
div {
width: 100px;
height: 100px;
background: yellowgreen;
position: absolute;
}
</style>
</head>
<body>
<div></div>
</body>
<script>
function interval(delay = 1000, callback) {
return new Promise(resolve => {
let id = setInterval(() => {
callback(id, resolve);
}, delay);
});
}
interval(100, (id, resolve) => {
const div = document.querySelector("div");
let left = parseInt(window.getComputedStyle(div).left);
div.style.left = left + 10 + "px";
if (left >= 200) {
clearInterval(id);
resolve(div);
}
})
.then(div => {
return interval(100, (id, resolve) => {
let width = parseInt(window.getComputedStyle(div).width);
div.style.width = width - 10 + "px";
if (width <= 20) {
clearInterval(id);
resolve(div);
}
});
})
.then(div => {
div.style.backgroundColor = "red";
});
</script>
</html>
3.接口数据缓存
Promise.hd = function(value) {
return new Promise(resolve => {
resolve(value);
});
};
Promise.hd("后盾人").then(value => {
console.log(value);
});
function query(name) {
const cache = query.cache || (query.cache = new Map());
if (cache.has(name)) {
console.log("走缓存了");
return Promise.resolve(cache.get(name));
}
return ajax(`http://localhost:8888/php/user.php?name=${name}`).then(
user => {
cache.set(name, user);
console.log("没走缓存");
return user;
}
);
}
query("后盾人").then(user => {
console.log(user);
});
ajax(http://localhost:8888/php/user.php?name=${name}
)是封装好的一个接口,返回值是promise
4.promise.all妙用多次请求数据
//根据用户批量获取用户资料
function getUsers(names) {
let promises = names.map(name => {
return ajax(`http://localhost:8888/php/user.php?name=${name}`);
});
return Promise.all(promises);
}
getUsers(["后盾人"]).then(users => {
console.log(users);
});
5.promise.allSettled过滤请求成功的数据
let promises = ["后盾人", "李四"].map(name => {
return ajax(`http://localhost:8888/php/user.php?name=${name}`);
});
Promise.allSettled(promises).then(values => {
let users = values.filter(user => {
return user.status == "fulfilled";
});
console.log(users);
});
6.promise队列
function queue(num) {
let promise = Promise.resolve();
num.map(v => {
promise = promise.then(_ => {
return v();
});
});
}
function p1() {
return new Promise(resolve => {
setTimeout(() => {
console.log("p1");
resolve();
}, 1000);
});
}
function p2() {
return new Promise(resolve => {
setTimeout(() => {
console.log("p2");
resolve();
}, 1000);
});
}
queue([p1, p2]);
reduce实现
function queue(num) {
num.reduce((promise, n) => {
return promise.then(_ => {
return new Promise(resolve => {
setTimeout(() => {
console.log(n);
resolve();
}, 1000);
});
});
}, Promise.resolve());
}
queue([1, 2, 3, 4]);
7.promise封装接口并渲染到页面
class User {
ajax(user) {
let url = `http://localhost:8888/php/user.php`;
return new Promise((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open("GET", `${url}?name=${user}`);
xhr.send();
xhr.onload = function() {
if (this.status == 200) {
resolve(JSON.parse(this.response));
} else if (this.status == 404) {
reject(new HttpError("用户不存在"));
} else {
reject("加载失败");
}
};
xhr.onerror = function() {
reject(this);
};
});
}
render(users) {
users.reduce((promise, user) => {
return promise
.then(_ => {
return this.ajax(user);
})
.then(user => {
return this.view(user);
});
}, Promise.resolve());
}
view(user) {
return new Promise(resolve => {
let h2 = document.createElement("h2");
h2.innerHTML = user.name;
document.body.appendChild(h2);
resolve();
});
}
}
new User().render(["后盾人", "向军"]);