promise对象解决回调地狱

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

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

而如今我这里使用promise对象来解决回调地狱函数

 

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

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

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

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

复制代码
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 里的回调函数it

相关文章
相关标签/搜索