React学习中Promise问题:如何让两个then块按顺序执行
问题:如何让Promise的then回调按顺序执行?
我昨日开始学习React,在Promise的使用上遇到了问题。以下是我的代码:
var p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(3) }, 2000); }) p1 .then(() => { setTimeout(() => { // First block console.log("This was executed.") }, 1000) }) .then(() => { // Second block console.log("This block is executed too."); })
请问如何修改代码,让第一个then块中的代码执行完成后,再执行第二个then块中的代码?
回答
嗨,我来帮你搞定这个问题~
你现在的代码里,第一个then回调里的setTimeout是异步操作,但这个then并没有返回一个新的Promise,所以Promise链会直接跳过这个异步操作,立刻执行第二个then。这就是为什么你会看到第二个console.log先输出的原因。
要让第二个then等待第一个then里的异步操作完成,你需要在第一个then中返回一个新的Promise,把setTimeout包裹进去,当异步操作完成时调用resolve,这样Promise链就会等待这个操作结束再继续执行下一个then。
修改后的代码如下:
var p1 = new Promise((resolve, reject) => { setTimeout(() => { resolve(3) }, 2000); }) p1 .then(() => { // 返回一个新的Promise,让Promise链等待异步操作完成 return new Promise((resolve) => { setTimeout(() => { // First block console.log("This was executed."); // 异步操作完成后调用resolve,触发下一个then resolve(); }, 1000); }); }) .then(() => { // Second block console.log("This block is executed too."); })
这样修改后,程序会先等待2秒完成p1的resolve,然后进入第一个then,等待1秒输出"This was executed.",resolve新Promise后,才会执行第二个then输出"This block is executed too.",完全符合你想要的顺序~
内容的提问来源于stack exchange,提问作者Carlos A. S. Moretti
相关产品推荐
相关产品推荐

