标签:接收 如何 意思 console jquer 开始 function reject gif
var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log(‘执行完成‘); resolve(‘随便什么数据‘); }, 2000); });
function runAsync(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ console.log(‘执行完成‘); resolve(‘随便什么数据‘); }, 2000); }); return p; } runAsync()
runAsync().then(function(data){ console.log(data); //后面可以用传过来的数据做些其他操作 //...... });
function runAsync(callback){ setTimeout(function(){ console.log(‘执行完成‘); callback(‘随便什么数据‘); }, 2000); } runAsync(function(data){ console.log(data); });
runAsync1() .then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return runAsync3(); }) .then(function(data){ console.log(data); });
runAsync1() .then(function(data){ console.log(data); return runAsync2(); }) .then(function(data){ console.log(data); return ‘直接返回数据‘; //这里直接返回数据 }) .then(function(data){ console.log(data); });
function getNumber(){ var p = new Promise(function(resolve, reject){ //做一些异步操作 setTimeout(function(){ var num = Math.ceil(Math.random()*10); //生成1-10的随机数 if(num<=5){ resolve(num); } else{ reject(‘数字太大了‘); } }, 2000); }); return p; } getNumber() .then( function(data){ console.log(‘resolved‘); console.log(data); }, function(reason, data){ console.log(‘rejected‘); console.log(reason); } );
getNumber() .then(function(data){ console.log(‘resolved‘); console.log(data); }) .catch(function(reason){ console.log(‘rejected‘); console.log(reason); });
getNumber() .then(function(data){ console.log(‘resolved‘); console.log(data); console.log(somedata); //此处的somedata未定义 }) .catch(function(reason){ console.log(‘rejected‘); console.log(reason); });
Promise .all([runAsync1(), runAsync2(), runAsync3()]) .then(function(results){ console.log(results); });
Promise .race([runAsync1(), runAsync2(), runAsync3()]) .then(function(results){ console.log(results); });
//请求某个图片资源 function requestImg(){ var p = new Promise(function(resolve, reject){ var img = new Image(); img.onload = function(){ resolve(img); } img.src = ‘xxxxxx‘; }); return p; } //延时函数,用于给请求计时 function timeout(){ var p = new Promise(function(resolve, reject){ setTimeout(function(){ reject(‘图片请求超时‘); }, 5000); }); return p; } Promise .race([requestImg(), timeout()]) .then(function(results){ console.log(results); }) .catch(function(reason){ console.log(reason); });
标签:接收 如何 意思 console jquer 开始 function reject gif
原文地址:https://www.cnblogs.com/onesea/p/13112790.html