Promise模拟请求

Promise 模拟请求

前言

​ 在正常开发需求的过程中,我们开发前端页面是和后端开发接口同步进行的,经常性的会遇到后端接口还没完成的情况下需要模拟请求来看一下页面完整的效果,本篇写的是自己使用 promise 模拟一个异步请求。

1. 模拟请求

1
2
3
4
5
6
7
8
9
10
11
12
13
const mockRequest = () => {
const data = [];
return new Promise((resolve) => {
setTimeout(() => {
for (let i = 0; i < 10; i++) {
data.push({
id: i.toString(),
});
}
resolve(data);
}, 1000);
});
};

2. 获取数据

  • async/await 同步写法获取
1
2
3
4
const loadData = async () => {
const res = await mockRequest();
console.log(res); // [{id: '1'},{id: '2'}, ... ,{id: '9'}]
};
  • 链式写法获取
1
2
3
4
5
const loadData = () => {
mockRequest().then((data) => {
console.log(data); // [{id: '1'},{id: '2'}, ... ,{id: '9'}]
});
};