function promiseClick(){
let p = new Promise(function(resolve, reject){
setTimeout(function(){
var num = Math.ceil(Math.random()*20); //生成1-10的随机数
console.log('随机数生成的值:',num)
if(num<=10){
resolve(num);
}
else{
reject('数字太于10了即将执行失败回调');
}
}, 2000);
})
return p
}
promiseClick().then(
function(data){
console.log('resolved成功回调');
console.log('成功回调接受的值:',data);
},
function(reason, data){
console.log('rejected失败回调');
console.log('失败执行回调抛出失败原因:',reason);
}
);
————————————————
<div onClick={promiseClick}>开始异步请求</div>
const promiseClick =()=>{
console.log('点击方法被调用')
let p = new Promise(function(resolve, reject){
//做一些异步操作
setTimeout(function(){
console.log('执行完成Promise');
resolve('要返回的数据可以任何数据例如接口返回数据');
}, 2000);
});
return p
}
————————————————
const p = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
reject('Refused the request!');
},0);
})
};
const p2 = function(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(p())
},0);
})
};
p2().then(val => {
console.info('Status switches to fulfilled');
console.info(val);
}, val => {
console.info('Status switches to reject');
console.info(val);
});
————————————————
var p1 = new Promise((resolve, reject) => {
console.log(1)
resolve()
})
var p2 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(2)
resolve()
}, 1000);
})
var p3 = new Promise((resolve, reject) => {
setTimeout(() => {
console.log(3)
resolve()
}, 1000);
})
Promise.all([p1, p2, p3]).then((result) => {
console.log("执行完毕");
})
async function imAsync(num) {
if (num > 0) {
return num // 这里相当于resolve(num)
} else {
throw num // 这里相当于reject(num)
}
}
imAsync(1).then(function (v) {
console.log(v); // 1
});
// 注意这里是catch
imAsync(0).catch(function (v) {
console.log(v); // 0
})
网友评论