foreword
Hello everyone, I'm Lin Sanxin, uses the most simple and easy-to-understand words to describe the most difficult knowledge points is my motto, is the premise of advanced is my original intention
Promise encapsulates the request
If you usually use Promise
encapsulate the request, then when you use this request function, it looks like this:
// 封装请求函数
const request = (url, params) => {
return new Promise((resolve, reject) => {
// ...do something
})
}
// 使用时
const handleLogin = () => {
request(
'/basic/login',
{
usename: 'sunshine',
password: '123456'
}
).then(res => {
// success do something
}).catch(err => {
// fail do something
})
}
As you can see, when your request is successful, the then
method will be called, and when your request fails, the catch
method will be called.
async/await
The emergence of Promise
solves many problems, but if there are too many requests and there are order requirements, it is inevitable that will be nested, and the readability is poor, such as:
const handleLogin = () => {
request(
'/basic/login',
{
usename: 'sunshine',
password: '123456'
}
).then(res => {
// 登录成功后获取用户信息
request(
'/basic/getuserinfo',
res.id
).then(info => {
this.userInfo = info
}).catch()
}).catch(err => {
// fail do something
})
So at this time, async/await
appeared. Its function is: performs asynchronous operation in a synchronous way. The above code can be rewritten using async/await
as:
const handleLogin = async () => {
const res = await request('/basic/login', {
usename: 'sunshine',
password: '123456'
})
const info = await request('/basic/getuserinfo', {
id: res.id
})
this.userInfo = info
}
In this way, the readability of the code is relatively high, and the nesting problem just now will not occur, but now there is another problem. Promise has an error callback of catch
to ensure what to do after the request error, but how to catch the error with async/await
Woolen cloth?
async-to-js
In fact, there is already a library async-to-js
that has done this for us. We can see how it does it. Its source code is only a dozen lines of . We should read its source code and learn its ideas.
The source code is very simple
/**
* @param { Promise } 传进去的请求函数
* @param { Object= } errorExt - 拓展错误对象
* @return { Promise } 返回一个Promise
*/
export function to(
promise,
errorExt
) {
return promise
.then(data => [null, data])
.catch(err => {
if (errorExt) {
const parsedError = Object.assign({}, err, errorExt)
return [parsedError, undefined]
}
return [err, undefined]
})
}
export default to
Source code summary:to
function returns a Promise and the value is an array. There are two elements in the array. If the element with index0
is not null, it means that the request0
an error. An error is a success.
easy to use
How can we use this to
function? It's actually very simple, it's just an example
const handleLogin = async () => {
const [resErr, res] = await to(request('/basic/login', {
usename: 'sunshine',
password: '123456'
}))
if (resErr) {
// fail do somthing
return
}
const [userErr, info] = await to(request('/basic/getuserinfo', {
id: res.id
}))
if (userErr) {
// fail do somthing
return
}
this.userInfo = info
}
So, if you look at the source code of some libraries occasionally, you can still learn something! ! !
Epilogue
I'm Lin Sanxin, an enthusiastic front-end rookie programmer. If you are motivated, like the front-end, and want to learn the front-end, then we can make friends and fish together haha, touch the fish group, add me, please note [Si No]
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。