promise的简单理解

2017-09-23  本文已影响0人  向前冲冲的蜗牛

构造函数

var thing = new Promise(function(){
  alert('hello');
});

上面的这个 function() 是会立刻被执行的。

resolve 和 reject

上面的函数中,可以接受两个参数,一个是 resolve 一个是 reject ,如下

var thing = new Promise(function(resolve, reject){
  resolve();// 当操作成功之后,我们会呼叫这个函数,这样 thing.then() 就会被执行
  reject();// 如果操作失败,我们呼叫这个函数,来触发 thing.catch()
});

尝试在chrome的Sources的Snippets(代码片段)中执行。chrome的代码片段可以随时随地的敲一段js代码,然后立即执行,以后不用在console中那么麻烦了。

image.png
var thing = new Promise(function(resolve, reject){
  console.log('Run!');
  setTimeout(function(){
    resolve()
  }, 3000);
});
thing.then(function(){
  console.log('thing.then()...');
});
thing.catch(function(){
  console.log('thing.catch()...');  
});

执行上面代码,可以看到,chrome 终端中会先打印出 Run! ,然后三秒后会打印出 thing.then ... 。如果把上面的 resolve() 改成 reject() , 那么得到执行的就是 thing.catch() 了。

此文章参考[好多视频的博客]:http://haoduoshipin.com/v/206/

上一篇 下一篇

猜你喜欢

热点阅读