js的三种异步方法
2021-03-14 14:29
标签:ons abc ISE 方法 error def time name console js的三种异步方法 标签:ons abc ISE 方法 error def time name console 原文地址:https://www.cnblogs.com/zhaofeis/p/12810294.html// 存在异步问题
let fn = () => {
let name = ‘张三‘;
setTimeout(() => {
return name;
}, 1000);
}
console.log(fn()); // undefined
// 第一种 回调函数
let fnCallback = (callback) => {
let name = ‘张三fnCallback‘;
setTimeout(() => {
callback(name);
}, 1000);
}
fnCallback((data) => {
console.log(data);
})
// 第二种 Promise
let fbPromise = new Promise((success, error) => {
let name = ‘张三fbPromise‘;
setTimeout(() => {
success(name);
}, 1000);
})
fbPromise.then((data) => {
console.log(data);
});
// 第三种 async await
let fbAsync = async () => {
let name = ‘张三fbAsync‘;
return new Promise((success, error) => {
setTimeout(() => {
success(name);
}, 1000);
})
}
async function main() {
let abc = await fbAsync();
console.log(abc);
}
main();
上一篇:http与https随笔