这里需要注意的是为什么不直接给p1等的变量直接赋值为promise对象,而是嵌套一层函数呢,原因是下一次请求需要依赖上一次请求的返回值,所以需要接收上一次的出参作为下一次请求的入参,那么就需要嵌套一层外围的函数,而这个函数的返回值一定要是一个promise对象,因为你还需要下一层的.then;
const p1 = (data) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data + 1)
console.log('s1')
}, 1000)
console.log('p1 finished')
})
}
const p2 = (data) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data + 1)
console.log('s2')
}, 1000)
console.log('p2 finished')
})
}
const p3 = (data) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data + 1)
console.log('s3')
}, 1000)
console.log('p4 finished')
})
}
const p4 = (data) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data + 1)
console.log('s4')
}, 1000)
console.log('p4 finished')
})
}
const p5 = (data) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(data + 1)
console.log('s5')
}, 1000)
console.log('p5 finished')
})
}
p1(0)
.then((data) => {
return p2(data)
})
.then((data) => {
return p3(data)
})
.then((data) => {
return p4(data)
})
.then((data) => {
return p5(data)
})
.then((data) => {
console.log(data)
})
.catch((err) => {
console.log(err)
})
当然你也可以用async和await结合来代替上面的方式
正确代码如下:
const request1 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 1
};
resolve(obj)
})
}
const request2 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 2
};
resolve(obj)
})
}
const request3 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 3
};
resolve(obj)
})
}
let res1 = 0, res2 = 0, res3 = 0;
const fuc = async function () {
res1 = await request1(100);
res2 = await request2((Number(res1.a) || 0 ) + 100);
res3 = await request3((Number(res2.a) || 0 ) + 100);
console.log(res3.a)
}
fuc()
错误的代码:
当然这里的错误也只是相对的错误,此处也使用了async和await是为了呈现输出的结果,大家不必纠结,有兴趣的小伙伴就可以来了解下这二者的不同之处
const request1 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 1
};
resolve(obj)
})
}
const request2 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 2
};
resolve(obj)
})
}
const request3 = (data) => {
return new Promise((resolve, reject) => {
const obj = {
a: data || 3
};
resolve(obj)
})
}
let res1 = 0, res2 = 0, res3 = 0;
const fuc = async function () {
res1 = request1(100);
res2 = request2((Number(res1.a) || 0 ) + 100);
res3 = await request3((Number(res2.a) || 0 ) + 100);
console.log(res3.a)
}
fuc()
除了promise以外建议刚接触 JavaScript 没多久的小伙伴最好也去了解下js的 事件循环机制,
地址在这里哦
→ 请戳我进行跳转