promise是让我们前一个事情完成就执行下一个事件,通过.then的方法调用这样子代码不会臃肿
promise的用法:
模版:
let
checkLogin
=
function
(){
return
new
Promise
(
function
(
resolve
,
reject
){
let
flag
=
document
.
cookie
.
indexOf
(
"userId"
)>-
1
?
true
:
false
; //这个document这个的用法就是查找这个userId的值
if
(
flag
){
resolve
({
status:
0
,
result:
true
})
}
else
{
reject
(
"this is error"
)
}
})
};
checkLogin
().
then
(
res
=>
{
if
(
res
.
status
==
0
){
console
.
log
(
"success login"
)
}
}).
catch
(
error
=>
{
console
.
log
(
`error:
${
error
}
`
)
})
当你promise要运用到依次调用的时候那么就在上一个函数返回成功后return 下一个promise函数
在最后利用.then调用 例如:
let
getUserInfo
=
function
(){
return
new
Promise
(
function
(
resolve
,
reject
){
let
userInfo
= {
userId :
"123"
};
resolve
(
userInfo
);
})
}
checkLogin
().
then
((
res
)
=>
{
if
(
res
.
status
==
0
){
console
.
log
(
"success login"
)
return
getUserInfo
();
}
}).
catch
(
error
=>
{
console
.
log
(
`error:
${
error
}
`
)
}).
then
(
res2
=>
{
console
.
log
(
`userId:
${
res2
.
userId
}
`
)
})
promise.all的用法:同时调用多个promise 调用多个的时候用数组传递 例如:
Promise
.
all
([
checkLogin
(),
getUserInfo
()]).
then
(([
res1
,
res2
])
=>
{
console
.
log
(
`result:
${
res1
.
result
}
`
)
console
.
log
(
`userId:
${
res2
.
userId
}
`
)
})