解决异步的几种实现方式
程序员文章站
2022-06-27 21:17:01
如下代码 2、回调函数 3、async await ......
如下代码
const request = function(){ let num = math.round(math.random()*100)/100; console.log(num); settimeout(function(){ if(num < 0.5){ return('1234567'); }else{ return('abcdefg'); } },500) } console.log(request()) //输出:0.31 // undefined
settimeout为异步函数,所以第二个返回值就打印为了undefined,因为不会等待计时器函数执行完成再执行外层的console.log(request())。
1、promise then
//解决方法一:promise then const request = function(){ var _this = this; let num = math.round(math.random()*100)/100; console.log( num ); return new promise( (resolve, reject) => { settimeout(function(){ num < 0.5 ? resolve('1234567') : reject('abcdefg'); }, 500); }); } request().then( val => { console.log( val ); }).catch( err => { console.log( err ); });
2、回调函数
const request = function(cb){ let num = math.round(math.random()*100)/100; console.log(num); settimeout(function(){ num < 0.5 ? cb('1234567') : cb('abcdefg'); },500) } var result = request(function(res){ console.log(res); })
3、async await
const request = async function(){ let num = math.round(math.random()*100)/100; console.log(num); const result = await aa(num); } function aa(num){ settimeout(function(){ console.log(num < 0.5 ? '1234567' : 'abcdefg'); },500) } request();