在 JavaScript 中,有时候会两次异步,希望第一次异步完成后,再开始执行第二次异步,这就要求嵌套,如果嵌套多了,代码就复杂了,此时可以用 Promise。
let p = new Promise(function (resolve, reject) { console.log("itpow"); resolve(); }); p.then(function (){ console.log(1); }).then(function (){ console.log(2); }).then(function (){ console.log(3); }).catch(function (){ console.log("catch"); });
显示结果:
itpow、1、2、3
如果将 resolve() 改为 reject(),则显示:
itpow、catch。
但是我认为上面的调用是错误的做法,为什么呢?继续看:
let p = new Promise(function (resolve, reject) { console.log("itpow"); resolve(); }); p.then(function (){ setTimeout(function() { console.log(1); }, 2000); }).then(function (){ setTimeout(function() { console.log(2); }, 1000); }).then(function (){ console.log(3); }).catch(function (){ console.log("catch"); });
显示结果:
itpow、3、2、1
我们可以看出,并没有按我们的 then 顺序执行,正确怎么写呢?
let p = new Promise(function (resolve, reject) { console.log("itpow"); resolve(); }); p.then(function (){ return new Promise(function (resolve, reject) { setTimeout(function() { console.log(1); resolve(); }, 2000); }); }).then(function (){ return new Promise(function (resolve, reject) { setTimeout(function() { console.log(2); resolve(); }, 1000); }); });
原来,then 中,也要 return new Promise,后面的 then 才能等前面的执行完毕。
即:then 中 return new Promise。