promise基础

来源:互联网 发布:谭铁牛 人工智能 编辑:程序博客网 时间:2024/06/15 22:02

promise简介微笑:

Promise的出现,原本是为了解决回调地狱的问题.

通过把异步中使用回调函数的场景改为了.then().catch()等函数链式调用的方式。基于promise我们可以把复杂的异步回调处理方式进行模块化。


promise原理生气:

其实promise原理说起来并不难,它内部有三个状态,分别是pendingfulfilledrejected 

pending是对象创建后的初始状态,当对象fulfill(成功)时变为fulfilled,当对象reject(失败)时变为rejected不可逆向,且一旦状态改变就不会再变


promise使用得意:

Promise对象拥有两个实例方法then()catch()

then方法可以接收两个参数, 第一个参数会添加到fulfill时调用的数组中,第二个参数添加到reject时调用的数组中。当promise状态fulfill时,会把resolve(value)中的value值传给调用的函数中,同理,当promise状态reject时,会把reject(reason)中的reason值传给调用的函数。例:


promise例子害羞:

//例子--模仿去读取一个jsonasync function asyncReadFile(int){    console.log(int);    //打印1let result = await new Promise((resolve,reject)=> {      console.log(2);     //打印2ajax({     method: 'get',     url: './file.json',     success(response) {        console.log(response);  //打印结果        resolve('resolved');     },                 fail(err) {                  reject(err);                         }  });}).then((msg)=>{console.log(msg+'!!!')});  //成功打印出resolved!!!    //result的值是await内部通过resolve传出来的值    console.log(3);   //打印3};asyncReadFile(1).then((msg='msg')=>{console.log(msg+'1');return 'msg'+'1'})  //打印msg1                  .then((msg)=>{console.log(msg+'2');return msg+'2'})   //打印msg12                  .then((msg)=>{console.log(msg+'3');throw new Error('404');return msg+'3'})  //打印msg123                  .catch((err)=>{console.error('错误是'+err)});    //打印'错误是404'
  结果如下:



promise注意点惊恐:

1.then方法会返回一个新的promise,下面的例子中p == p1将返回false,说明p1是一个全新的对象。虽然它也是链式调用的,它是在新的对象上添加成功或失败的回调,这与jQuery中的链式调用不同。

2. 如果promise.then(undefined,fnFail).then(fnSuccess)中resolve()调用成功函数 , 可以调用到fnSuccess函数 , 同理在reject中也可以这么执行. 当对应的参数不为函数时,会将前一promise的状态和值传递下去。奋斗

3.所以我们可以在多个then之后添加一个catch方法,这样前面只要reject或抛出异常,都会被最后的catch方法处理。




原创粉丝点击