React项目配置7(ES7的Async/Await的使用)


本教程总共6篇,每日更新一篇,请关注我们!你可以进入历史消息查看以往文章,也敬请期待我们的新文章!


1、React项目配置1(如何管理项目公共js方法)---2018.01.11


2、React项目配置2(自己封装Ajax)---2018.01.12


3、React项目配置3(如何管理项目API接口)---2018.01.15


4、React项目配置4(如何在开发时跨域获取api请求)---2018.01.16


5、React项目配置5(引入MockJs,实现假接口开发)---2018.01.17


6、React项目配置6(前后端分离如何控制用户权限)---2018.01.18


7、React项目配置6(ES7的Async/Await的使用)---2018.01.19(新增)


开发环境:Windows 8,node v8.9.1,npm 5.5.1,WebStorm 2017.2.2


我们今天讲下ES7的Async/Await的使用!

1、首先需要改造下AJAX请求

    我们新建 xmlNative.js文件,把公共部分抽取出来!

const xmlNative = (opt, type) => {
opt = opt || {};
   opt.method = opt.method.toUpperCase() || 'POST';
   opt.url = opt.url || '';
   opt.async = opt.async || true;
   opt.data = opt.data || null;
   opt.success = opt.success || function () {
};
   let xmlHttp = new XMLHttpRequest();
   if (opt.method.toUpperCase() === 'POST') {
xmlHttp.open(opt.method, opt.url, opt.async);
       xmlHttp.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
       xmlHttp.send(JSON.stringify(opt.data));
   } else if (opt.method.toUpperCase() === 'GET') {
let params = [];
       for (let key in opt.data) {
params.push(key + '=' + opt.data[key]);
       }
let postData = params.join('&');
       xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
       xmlHttp.send(null);
   }
if (type === 1) {
return new Promise((resolve, reject) => {
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
let responseText = JSON.parse(xmlHttp.responseText);
                       if (responseText.code === 0) {
resolve(responseText.data)
} else {
reject(responseText.message)
}
} else {
reject(JSON.parse(xmlHttp.responseText), xmlHttp.status)
}
}
};
       })
} else {
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
opt.success(JSON.parse(xmlHttp.responseText), xmlHttp.status)
} else {
opt.error(JSON.parse(xmlHttp.responseText), xmlHttp.status)
}
}
};
   }

};
export default xmlNative



2.修改之前的 apiRequest.js

import xmlNative from './xmlNative'
import apiManager from './apiManager'

const ajax = (url, method, data, successCB, errorCB) => {
let dataJson = {
version: "1.0.0",
       data: data
};
   return xmlNative({
method: method,
       url: url,
       data: dataJson,
       success: (data, status) => {
if (data.code === 0) {
successCB && successCB(data, status)
} else {
errorCB ? errorCB(data, status) : console.log(data, status)
}
},
       error: (data, status) => console.log(status, status)
});
};
const apiRequest = {
get: (apiName, data, successCB, errorCB) => ajax(apiManager[apiName], "get", data,
       data => successCB && successCB(data.data, data.systemDate),
       errorCB),
   post: (apiName, data, successCB, errorCB) => ajax(apiManager[apiName], "post", data,
       data => successCB && successCB(data.data, data.systemDate),
       errorCB)
};
export default apiRequest;

3.新建apiRequestAsync.js

import xmlNative from './xmlNative'
import apiManager from './apiManager'

const ajax = (url, method, data) => {
let dataJson = {
version: "1.0.0",
       data: data
};
   return xmlNative({
method: method,
       url: url,
       data: dataJson
}, 1);
};
const apiRequestAsync = {
get: (apiName, data) => ajax(apiManager[apiName], "get", data),
   post: (apiName, data) => ajax(apiManager[apiName], "post", data)
};
export default apiRequestAsync;

到这里就封装完了,我讲解下一些地方,如果没讲到的地方,大家不懂的可以留言问我!

if (type === 1) {
return new Promise((resolve, reject) => {
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState === 4) {
if (xmlHttp.status === 200) {
let responseText = JSON.parse(xmlHttp.responseText);
                   if (responseText.code === 0) {
resolve(responseText.data)
} else {
reject(responseText.message)
}
} else {
reject(JSON.parse(xmlHttp.responseText), xmlHttp.status)
}
}
};
   })

这个type完全是自定义的,type===1的时候,返回一个Promise,因为await等待的就是一个 Promise!

4.我们来测试一下

先看看原来的请求是否还正常

一切正常!

5.为什么要用 es7 async await

它主要是为了解决如下场景:

比如需求是我的请求的某个参数是需要上一个请求的结果:

类是于这样:

这样请求下去,会进入到回调地域里!

所有用es7 async await来解决这个问题

6、那怎么写呢?

其实也很简单,之前我们已经封装好了,我们来写下试试!

这里需要安装一个依赖,

npm i -S babel-polyfill

引入

import "babel-polyfill";
import apiRequestAsync from '../../../public/js/apiRequestAsync';

书写 es7 async await

async handleTodoList() {
let todoList = await apiRequestAsync.post('todoList');
   this.setState({list: todoList.list});
   let todoList1 = await apiRequestAsync.post('todoList');
   console.log(todoList1);
   let todoList2 = await apiRequestAsync.post('todoList');
   console.log(todoList2);
}



OK,看下浏览器效果

它渲染了 todolist,也打印出了todoList1及todoList2。

本文完 

禁止擅自转载,如需转载请在公众号中留言联系我们!

感谢童鞋们支持!

如果你有什么问题,可以在下方留言给我们!