promise对象解决回调地狱

先放一张图片感受一下回调地狱

看起来是真的很让人头痛的东西

而现在我这里使用promise对象来解决回调地狱

采用链式的 then,可以指定一组按照次序调用的回调函数。

这时,前一个 then 里的一个回调函数,返回的可能还是一个 Promise对象(即有异步操作),

这时后一个回调函数,就会等待该 Promise对象的状态发生变化,才会被调用。

由此实现异步操作按照次序执行。

复制代码
var sayhello = function (name) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      console.log(name);
      resolve();  //在异步操作执行完后执行 resolve() 函数
    }, 1000);
  });
}
sayhello("first").then(function () {
  return sayhello("second");  //仍然返回一个 Promise 对象
}).then(function () {
  return sayhello("third");
}).then(function () {
  console.log('end');
}).catch(function (err) {
  console.log(err);
})
//输出:first  second  third end
复制代码

上面代码中,第一个 then 方法指定的回调函数,返回的是另一个Promise对象。

这时,第二个then方法指定的回调函数,就会等待这个新的Promise对象状态发生变化。

如果变为resolved,就继续执行第二个 then 里的回调函数

原文地址:https://www.cnblogs.com/mlw1814011067/p/10750103.html