异步进化
2020-09-12 本文已影响0人
yimi珊
例如:
获取用户数据;
再根据用户数据,获得订单数据;
再根据订单数据,获得商品数据;
setTimeout
//回调地狱
setTimeout(()=>{
let users = '用户数据'
console.log(users);
setTimeout(() => {
let orders = '订单数据'
console.log(orders);
setTimeout(() => {
let goods = '商品数据'
console.log(goods);
}, 1000);
}, 1000);
},1000);
生成器函数
function getUsers(){
setTimeout(() => {
let data = '用户数据';
console.log(data);
//调用next方法,并且将数据传入
iterator.next(data);
}, 1000);
}
function getOrders(){
setTimeout(() => {
let data = '订单数据';
console.log(data);
iterator.next(data);
}, 1000);
}
function getGoods(){
setTimeout(() => {
let data = '商品数据';
console.log(data);
iterator.next(data);
}, 1000);
}
//声明生成器函数
function * gen(){
let users = yield getUsers();
let orders = yield getOrders();
let goods = yield getGoods();
}
//调用生成器函数
let iterator = gen();
iterator.next();
Promise对象
const p = new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '用户数据';
console.log(data);
resolve(data);
}, 1000);
});
p.then(value=>{
return new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '订单数据';
console.log(data);
resolve([value,data]);
}, 1000);
});
}).then(value=>{
return new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '商品数据';
console.log(data);
resolve([value,data]);
}, 1000);
});
});
Async...await
function getUsers(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '用户数据';
// console.log(data)
resolve(data);
}, 1000);
})
}
function getOrders(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '订单数据';
resolve(data);
}, 1000);
})
}
function getGoods(){
return new Promise((resolve,reject)=>{
setTimeout(() => {
let data = '商品数据';
resolve(data);
}, 1000);
})
}
async function main(){
let users = await getUsers();
console.log(users);
let orders = await getOrders();
console.log(orders);
let goods = await getGoods();
console.log(goods);
}
main();