Promise学习笔记

定义

Promise是一个对象,它代表了一个异步操作的最终完成或者失败。本质上,Promise是一个被某些函数传入的对象,我们附加回调函数使用它,而不是将回调函数传入那些函数内部。

语法

new Promise( function(resolve, reject) {...} /* executor */  );

参数

  • executorexecutor是带有resolvereject两个参数的函数。Promise构造函数执行时立即调用executor函数,resolvereject两个函数作为参数传递给executorresolvereject函数被调用时,分别将Promise的状态改为fulfilled(完成)或者rejected(失败)。executor内部通常会执行一些异步操作,一旦异步操作执行完毕,要么调用resolve函数来将promise状态改成fulfilled,要么调用reject函数来将promise状态改成rejected。如果在executor函数中抛出一个错误,那么该promise 状态为rejectedexecutor函数的返回值被忽略。

假设我们有一个获取用户列表的异步接口请求方法,原始的方法是使用回调函数的方式请求成功或者失败的结果

  function requestSuccess(){
    console.log('获取用户列表成功')
  }
  function requestFailure(){
    console.log('获取用户列表失败')
  }

  requestUserList(url,requestSuccess,requestUserList)

这种情况下,我们可以使用最新的方式就是返回一个Promise,使得你可以把你的回调函数绑定在该Promise上

requestUserList(url).then(requestSuccess,requestFailure)

链式调用

连续执行两个或者多个异步操作是一个常见的需求,在上一个操作执行成功之后,开始下一个的操作,并带着上一步操作所返回的结果。

 const promise = doSomething()
  // .then()方法返回一个全新的promise
 const newPromise = doSomething().then(successCallback,failureCallback)

回调地狱

doSomething(function(result) {
  doSomethingElse(result, function(newResult) {
    doThirdThing(newResult, function(finalResult) {
      console.log('Got the final result: ' + finalResult);
    }, failureCallback);
  }, failureCallback);
}, failureCallback);

通过Promise可以解决这样的异步回调

// 使用了箭头函数
doSomething()
.then(result => doSomethingElse(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
  console.log(`Got the final result: ${finalResult}`);
})
.catch(failureCallback);

错误的传递

在原先的回调地狱中,对于失败的回调需要执行多次,而在Pormise链中,只要在尾部的一个调用即可

doSomething()
.then(result => doSomethingElse(value))
.then(newResult => doThirdThing(newResult))
.then(finalResult => console.log(`Got the final result: ${finalResult}`))
.catch(failureCallback);

使用async和await
在使用async和await处理异步请求的时候,需要使用try-catch来捕获程序的异常

async function foo() {
  try {
    let result = await doSomething();
    let newResult = await doSomethingElse(result);
    let finalResult = await doThirdThing(newResult);
    console.log(`Got the final result: ${finalResult}`);
  } catch(error) {
    failureCallback(error);
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值