如下代碼 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();