async-events-emitter

Place look https://www.npmjs.com/package/promise-to-async-events


License
ISC
Install
npm install async-events-emitter@1.0.7

Documentation

AsyncEmitter

AsyncEmitter 可以把异步请求包装为一个可观察源,这意味着可以设置多个观察者同时观察同一个异步请求,每个观察者负责自己的逻辑(比如加载中状态、通用错误处理等),从而做到逻辑分离。

使用 AsyncEmitter 的另一个好处是统一异步动作的状态规范,站点中其他的异步动作同样可以使用此规范(继承AsyncEmitter), 比如“多个异步请求需要合并成一个原子操作就尤为实用”。

异步状态生命周期

  Async request life cycle

  --> SEND_BEFORE ------------------- COMPLETE ----- SUCCESS
    |                                          |
    |                                          |---- ERROR
    |                                          |
    |0-------------- PROGRESS --------------100|

使用 AsyncEmitter

  • 安装

  npm install async-events-emitter

  • 在 React 中使用
import React from 'react'
import AsyncEmitter from 'async-events-emitter'


class App extends React.Component{
  constructor(props){
    super(props)
    this.state = {
      userName:""
    }
  }

  componentDidMount(){

    new AsyncEmitter( fetch("http://user.info") )
    .subscribe(this.refs['loading'])//处理加载中状态
    .subscribe(this.refs['globalTips'])//处理错误
    .subscribe((result)=>{
      this.setState({
        userName:result.userName
      })
    })

  }

  render(){

    return (
      <div>
        <Loading ref="loading" />
        <Tips ref="globalTips" />
        {this.state.userName}
      </div>
    )

  }
}
  • 全部API
  new AsyncEmitter(fetch("http://api.get.user.info"))
  .subscribe({
      onSendBefore:()=>{
        // ...show loading
      },
      onComplete:()=>{
        // ... hide loading
      }
  })
  //如果你在使用模块化的开发方式,比如React处理loading更简单
  .subscribe(this.refs['loading'])
  .subscribe({
    onError:()=>{
      //...处理通用异常
    }
  })
  //处理业务逻辑
  .subscribe({
    onSuccess:(result)=>{
      if(result.code == 0){
        //正确处理UI
      }else{
        //处理业务错误
      }
    }
  })
  //发送
  .fetch();

API

  • 链接 fetch
  var asyncRequest = new AsyncEmitter( fetch("http://www.baidu.com") )
  • 链接 jQuery
  var asyncRequest = new AsyncEmitter( $.ajax("http://www.baidu.com") )
  • 链接任意 Promise 请求
  var asyncRequest = new AsyncEmitter( JSONP("http://www.baidu.com") )

方法

  • asyncRequest.subscribe( observer )
  asyncRequest.subscribe({
    onSendBefore:()=>{}
    onComplete:(data)=>{}
    onProgress:(progress)=>{ /**0-100*/}
    onSuccess:(data)=>{ /*response.data*/ }
    onError:(err)=>{err}
  })
  • asyncRequest.subscribe( fn )
  asyncRequest.subscribe((data)=>{
      // onSuccess
  })
  • asyncRequest.fetch()
  //发送请求
  asyncRequest.fetch()