Promise是个好东西,但是then来then去的很讨厌,所以一直想要封装一个模块出来,只要给url给参数,就能直接给我把从后台get到的结果吐出来。
可惜才疏学浅,对promise的理解一直不深刻,直到最近在刷别的知识点的视频的时候忽然有了灵感。
肯定会有更优雅的实现方式。只是记录一下自己以后找起来方便:
import axios from 'axios'
const API = {
/*Main URL*/
main: 'http://XXX',
/*Sub URL for each action*/
'REPLAY_HELLO': 'reply_hello',
/*GET function*/
async GET(action, params) {
let params_str = '';
Object.keys(params).forEach(param => params_str += `${param}=${params[param]}&`)
const url = API.main + API[action] + '?' + params_str;
console.log(action, url);
// return false;
axios.defaults.withCredentials = true;
const get_back = await axios.get(url)
console.log('API, GET', get_back)
if(get_back.status == 200){
/*communicate with backend successfully*/
const result = get_back.data;
// there still a "status" in return data, using to identify if there is business level issue
if(result.status != 0){
alert(result.msg);
return false;
}
return result.data;
}else{
/*communicate with backend failed*/
alert(`Error happened during ${action}`);
return get_back;
}
}
}
export default API;
如何使用:
submitSearch = async (formValues) => {
const test = await API.GET('REPLAY_HELLO', {'name': 'jerry'})
console.log('try await', test)
}
结果:
我的这个例子里,返回的data里头没有status这一项,所以try await后面是false。