标签:lse res settime function catch 原型 and lan eject
Promise是异步编程的一种解决方案,也是ES6的写法,它其实是一个构造函数,自己身上有all、reject、resolve这几个方法,原型上有then、catch等方法。
不多说,直接上代码:
const promise = new promise(function(resolve, reject){
setTimeout(()=>{
const num = Math.random();
if(num < 0.5){
resolve("成功"+num)
}else{
reject("失败"+num)
}
},3000)
})
promise.then(function(res){
console.log(res);
}).catch(function(err){
console.log(err)
})
简单处理下promise.all的用法:
let promise1 = new Promise(function(resolve) { resolve(1); });
let promise2 = new Promise(function(resolve) { resolve(2); });
let promise3 = new Promise(function(resolve) { resolve(3); });
let promiseAll = Promise.all([promise1, promise2, promise3]); promiseAll.then(function(res) { console.log(res); });
标签:lse res settime function catch 原型 and lan eject
原文地址:https://www.cnblogs.com/zxm1993/p/13951258.html