在react+redux+axios项目中使用async/await

Async/Await

Async/Await是还没有正式公布的ES7标准新特性。简而言之,就是让你以同步方法的思惟编写异步代码。对于前端,异步任务代码的编写经历了 callback 到如今流行的 Promise ,最终会进化为 Async/Await 。虽然这个特性还没有正式发布,可是利用babel polyfill咱们已经能够在应用中使用它了。前端

http://www.tuicool.com/articles/B77zAbereact

如今假设一个简单的React/Redux应用,我将引入 Async/Await 到其代码。ios

Actions

此例子中有一个建立新文章的 Action ,传统方法是利用 Promise 结合 Redux-thunk 中间件实现。redux

import axios from 'axios'

export default function createPost (params) {  
    const success = (result) => {
        dispatch({
            type: 'CREATE_POST_SUCCESS',
            payload: result
        })
        return result
    }

    const fail = (err) => {
        dispatch({
            type: 'CREATE_POST_FAIL',
            err
        })
        return err
    }

    return dispatch => {
        return axios.post('http://xxxxx', params)
        .then(success)
        .catch(fail)
    }
}

如今将它改写为 async/await 的实现:axios

import axios from 'axios'

export default function createPost (params) {  
    const success = (result) => {
        dispatch({
            type: 'CREATE_POST_SUCCESS',
            payload: result
        })
        return result
    }

    const fail = (err) => {
        dispatch({
            type: 'CREATE_POST_FAIL',
            err
        })
        return err
    }

    return async dispatch => {
        try {
            const result = await axios.post('http://xxxxx', params)
            return success(result)
        } catch (err) {
            return fail(err)
        }
    }
}

async和await是成对使用的,特色是使代码看起来和同步代码相似。浏览器

Components

一样,在React组件中,也比较一下 Promise 和 Async/Await 的方法异同。babel

传统地使用 Promise :异步

import React, { Component } from 'react'  
import { connect } from 'react-redux'  
import { createPost } from '../actions/post'

class PostEditForm extends Component {  
    constructor(props) {
        super(props)
    }

    contributePost = e => {
        e.preventDefault()

        // .... get form values as params

        this.props.createPost(params)
        .then(response => {
            // show success message
        })
        .catch(err => {
            // show error tips
        })
    }

    render () {
        return (
            <form onSubmit={this.contributePost}>
                <input name="title"/>
                <textarea name="content"/>
                <button>Create</button>
            </form>
        )
    }
}

export default connect(null, dispatch => {  
    return {
        createPost: params => dispatch(createPost(params))
    }
})(PostEditForm)

若是使用 Async/Awaitasync

import React, { Component } from 'react'  
import { connect } from 'react-redux'  
import { createPost } from '../actions/post'

class PostEditForm extends Component {  
    constructor(props) {
        super(props)
    }

    async contributePost = e => {
        e.preventDefault()

        // .... get form values as params

        try {
            const result = await this.props.createPost(params)
            // show success message
        } catch (err) {
            // show error tips
        }
    }

    render () {
        return (
            <form onSubmit={this.contributePost}>
                <input name="title"/>
                <textarea name="content"/>
                <button>Create</button>
            </form>
        )
    }
}

export default connect(null, dispatch => {  
    return {
        createPost: params => dispatch(createPost(params))
    }
})(PostEditForm)

能够见得,两种模式, Async\Await 的更加直观和简洁,是将来的趋势。可是目前,还须要利用babel的 transform-async-to-module-method 插件来转换其成为浏览器支持的语法,虽然没有性能的提高,但对于代码编写体验要更好。post

 

原文连接:http://blog.csdn.net/sinat_17775997/article/details/73526610

相关文章
相关标签/搜索