解决异步的几种实现方式

如下代码

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())。

豌豆资源搜索网站https://55wd.com 电脑刺绣绣花厂 ttp://www.szhdn.com

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();
posted @ 2020-09-20 14:53  酷儿q  阅读(204)  评论(0编辑  收藏  举报