使用 Promise 是需要实例化 Promise 对象,参数是一个函数。
通过函数参数 t 和 f,返回不同状态。执行成功返回 T,执行失败返回 F。
使用 then 接收返回值,两个参数分别对应成功和失败。
1
2
3
4
5
6
7
8
9const getUserInfo = () => new Promise((t,f) => {
t({ id: 1, nickname: 'MiYou' });
})
getUserInfo().then(res => {
console.log(res);
},rej => {
console.log(rej);
})1
2
3
4
5
6
7
8
9const getUserInfo = () => new Promise((t,f) => {
f({ code: 500, msg: 'Error' });
})
getUserInfo().then(res => {
console.log(res);
},rej => {
console.log(rej);
})