// 存在异步问题
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();