var test = asyncfunction() { let res = awaitsleep(3000); console.info(res); console.info("hehe"); };
var test2 = asyncfunction() { let res = awaitsleep(1000); //reject返回了一个错误 console.log(res); //控制太执行显示的是 ”Uncaught (in promise) 10000“ console.info("hehe"); };
// try catch 捕捉错误 var test3 = asyncfunction() { try { let res = awaitsleep(1000); //reject 错误 console.log(res); // 只显示reject返回值,不会提示说是 "Uncaught" console.info("hehe"); //不会执行 } catch (err) { console.error(err); } };
var httpRequest = function(URL) { returnnewPromise(function(resolve, reject){ var x = $.ajax({ type: "GET", url: URL, }); /* x.done(function(res){ if(res.error.returnCode == "0") resole(res.data); reject(res.error.returnCode); }); */ if(x) resolve(x); reject("10000"); }); }
var req = asyncfunction() { try { console.log("开始请求"); //var res = await httpRequest("http://www.baidu.com"); //因为在浏览器端存在跨域 let res = awaithttpRequest("http://localhost/sites/JDBToolsPlatform/api/processQualityReport/reportDataDetail.php?beginDate=2017-06-01&endDate=2017-06-30"); console.log(res); //获得返回的数据 //console.log(typeof res); //返回的json类型:string //console.log(JSON.parse(res).error.returnCode); //获取返回状态码 console.log("请求结束。。。"); }catch (err) { console.log(err); } };
异步函数
客户端fetch API, 一种替代 XMLHttpRequest 检索文件的方案.
1 2 3 4 5 6 7 8 9 10
asyncfunctionfetchJson(url) { try { let request = awaitfetch(url); //fetch函数返回的就是一个Promise对象 let text = await request.text(); returnJSON.parse(text); } catch (error) { console.log(`ERROR: ${error.stack}`); } }
1 2 3 4 5 6 7 8
var t = fetchJson("http://localhost/sites/JDBToolsPlatform/api/processQualityReport/reportDataDetail.php?beginDate=2017-06-01&endDate=2017-06-30"); // console.inf(typeof t); // "object" t是一个Promise对象