在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

相關文章
相關標籤/搜索