开发者联盟思考Web 前端开发

关于Promise的一些

2018-01-25  本文已影响156人  Pursue

github同步

1.定义

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

为什么要重新从定义回顾,是因为我觉得就是因为定义太过于简单,所以细节容易被忽略。

比如怎么才算最终的状态?怎么更好的处理异常?如何兼容多个浏览器?

恰巧最近在整理项目代码时,发现了Promise的一些小坑,特地重新回顾复习一遍,希望下面的介绍可以让你有所收获!

2.基础用法


const timeDefer = milliseconds => new Promise(resolve => {
    setTimeout(() => {
       resolve() 
    }, milliseconds)
   }
)

这是一个简单的用法,可以用来模拟异步请求。

假设用在类似React的组件中,异步请求回来后需要render部分UI,我们经常会在回调里写类似this.renderTable(response)处理逻辑。

那么让我们检测下吧。


const timeDefer = milliseconds => new Promise(resolve => {
    console.log(this)
    setTimeout(() => {
      resolve() 
    }, milliseconds)
  }
)

timeDefer(1000).then(() => console.log('success'))

//undefined
//success

糟糕,在scope内拿不到this。

你也许会说你由于箭头函数的问题,好,我们换为ES5。


var hanlder = {
  method: function(milliseconds) {
    return function(resolve) {
      console.log(this)
      setTimeout(function(){
        resolve() 
      }, milliseconds)
    }
  }
}

function timeDefer(milliseconds) {    
  return new Promise(hanlder.method(milliseconds))
} 

timeDefer(1000).then(() => console.log('success'))

//undefined
//success

依然没有获取到,所以,这必须和箭头函数无关。

注意:我的运行环境为webpack编译后的runtime上下文内。

再换一种思路试试吧。

<script>

const timeDefer = milliseconds => new Promise(resolve => {
    console.log(this)
    setTimeout(() => {
      resolve() 
    }, milliseconds)
  }
)

timeDefer(1000).then(() => console.log('success'))

</script>

//window
//success

如上,我直接写在了页面里,结果是你想的吗?

很惊奇吧!没错,Promise回调内的this是和上下文有关系的,不一定具体是什么,但应该是global

3.简单请求:fetch

我们经常会用一些fetch的库,如whatwg-fetch,其实fetch就是基于Promise的一种实现,而许多浏览器也支持原生的fetch,如Chrome;同样的,像IE这种非主流当然肯定是不支持的,所以这些库往往会帮我们去做polyfill。

fetch请求资源的用法如下:


const getJSON = url => fetch(url)
      .then(response => response.json())


getJSON('/data.json')
  .then(json => console.log('success1', json))
  .catch(error => console.log('failed0'))

这里唯一需要注意的一点就是response.json(),它返回的是一个Promise对象,请切记这一点。

对于Promise后面跟的链式thenable函数,一般有两种写法,上述等同于


getJSON('/data.json')
  .then((response, error) => {
      //do something
  })

第一首较第二种来说更加直观清晰,所以大多数情况下都比较推荐第一种。

但第一种的写法有一些规则需要注意:


getJSON('/data.json')
  .then(json => console.log('success1', json))
  .then(json => console.log('success1', json))
  .catch(error => console.log('failed0'))

//success1
//success1


getJSON('/data.json')
  .catch(error => console.log('failed0'))
  .then(json => console.log('success1', json))

//failed0
//success, undefined

这种情况最容易犯错,而且还不易排查,确保你的异常处理作为链式收尾。

对于这个case,希望你可以先自己猜猜,在看输出。


const getJSON = url => fetch(url)
      .then(response => {
          console.log('success0', response)
          return response.json()
      })
      .then(json => {
        console.log('success1', json)
      })
      .catch(error => {
        console.log('failed0')
      })


getJSON('/data1.json')//无效url,404

//success: 0
//failed0

你没有看错,对于fetch(尤其是使用原生)来说,404是‘成功‘的请求,并不会直接进catch。

类似的问题许多库的issue里都提到:Why both of then and catch are invoked when reponse status is 404

因此正确的处理应该是:


const getJSON = url => fetch(url)
      .then(response => {
        if (response.status === 200) {
          console.log('success0', response)
          return response.json()
        }
      })
      .then(json => {
        console.log('success1', json)
      })
      .catch(error => {
        console.log(error, 'failed0')
      })


4.高级用法:链式

Promise最大的作用就是解决了地狱回掉,并且给异步方法提供了优美的语法糖。

链式基本写法:


const success = () => Promise.resolve({data: {}})

const failed = () => Promise.reject({error: {}})

success()
  .then(response => console.log(response))
  .catch(error => console.log(error))

success()
  .then((response, error) => {
    console.log(response, error)
  })

Promise.resolvePromise.reject分别返回一个已经成功/失败的promise对象,我在此用来模拟成功/失败的请求。

基于上面的回顾,几个小demo可以用来检测下自己对链式的掌握:


success('success0')
  .then(response => console.log(response))
  .then(response => console.log(response))
  .then(response => console.log(response))
  .then(response => console.log(response))

//success
//undefined
//undefined
//undefined

这个应该很好理解,我在上面已经提到了then的传递性


success('0')
  .then(response => {
    console.log('failed', response)
    failed(response)
  })
  .catch(error => {
    console.log('recovery', error)
    return success(error)
  })
  .then((response, error) => console.log(response, error))

// failed 0
// undefined, undefined

这个结果是不让你懵逼了,如果是,那么先看下个例子。


success('0')
  .then(response => {
    console.log('failed', response)
    return failed(response)
  })
  .catch(error => {
    console.log('recovery', error)
    return success(error)
  })
  .then((response, error) => console.log(response, error))

// failed 0
// recovery 0
// 0 undefined

没错,差别就在于一个return,也许你一个小的手误就会导致一个大bug。

所以切记:如果在Promise的回掉逻辑里依然是是Promise,且希望有链式的后续处理,记得一定要返回该实例。

有了上面的基本知识,我们用最后一个Demo来结束本文:


const getJSON = url => fetch(url)
  .then(response => response.json())//.json() will return a promise
  .catch(error => console.log(error))

假设getJSON('/data.json')会返回一个形如:


{
    urls: [
        'file1.md',
        'file2.md',
        'file3.md',
        ...
        'file12.md'
    ]
}

的json对象,包含接下来需要请求的资源。

我们在回调里的实现方式如下:


getJSON('/data.json')
  .then(data => {
    data.urls.forEach(url => {
      getJSON(url)
    });
  })


getJSON('/data.json')
  .then(data => {
    let thenableRequest = Promise.resolve();
    data.urls.forEach(url => {
      thenableRequest.then(() => getJSON(url))
    });
  })


getJSON('/data.json')
  .then(data => {
    let thenableRequest = Promise.resolve();
    data.urls.forEach(url => {
      thenableRequest = thenableRequest.then(() => getJSON(url))
    });
  })

等同于

getJSON('/data.json')
  .then(data => {
    data.urls.reduce(
      (thenable, url) => thenable.then(() => getJSON(url)),
       Promise.resolve()
      )
  })

如果你能一口气说出其中的区别,或者告诉我Network中资源请求的顺序,那么请忽略本文。

第一种:

并行请求 ,但不能保证顺序,所以结果不可预期,如果这不是请求资源,而是数个有依赖顺序的API,那结果肯定不能满足你。

第二种:

其实和第一种没有太大区别,只是稍微用链式重构了下,但实质并没有变。

第三种:

getJSON每次都会返回一个新的Promise对象,你可以将其看作是reduce的结果,这种链式最终的结果是串行请求所有资源,即先file1.md, file2.md, ... file12.md,如果用Network去查看,可以发现它是依次请求的,保证的顺序。

这三种方法其实就在解决一个问题,而也就是为什么有Promise.all的原因了。

Promise.all既做保证了顺序也做了异常处理:所有的请求都成功了才能拿到最终结果,否者则会reject。

利用Promise.all改写如下:


getJSON('/data.json')
  .then(data => Promise.all(data.urls.map(url => getJSON(url))))
  .then(responseArray => console.log('responseArray', responseArray))

上一篇下一篇

猜你喜欢

热点阅读