参考:
typescript
fun() {
return new Promise((resolve, reject) => {
let succ = Math.random() > 0.5
setTimeout(() => {
if (succ) {
resolve(null)
}
else {
reject(null)
}
}, 2000)
});
}
test() {
this.fun().then((data) => {
//成功处理resolve
}, (data) => {
//失败处理reject
})
//或者
this.fun().then((data) => {
//成功处理
}).catch((error: Error) => {
//失败处理
})
}
//加载多个
fun2() {
let loadArr = []
return new Promise((resolve, reject) => {
Promise.all(loadArr).then(() => {
//loadArr都执行完之后
resolve(null);
}).catch((error: Error) => {
//loadArr出错
resolve(null);
})
});
}
//链式调用
test2() {
let p = new Promise(resolve => {
setTimeout(() => {
resolve("success 1")
}, 2000)
})
p.then((info) => {
// 此处继续返回一个promise对象,形成链式调用
return new Promise(resolve => {
console.log("info = ", info)
setTimeout(() => {
resolve("success 2")
}, 2000)
})
}).then((info) => {
console.log("info = ", info)
}).catch((error: Error) => {
//失败处理
})
}