learning_cesium/ES6.html

89 lines
3.1 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
// asnyc函数声明方式在函数前面添加async关键字即可
// async function fn(){
// // 1、只要返回的结果不是一个Promise对象则返回的结果都是一个成功的Promise对象
// // 返回一个字符串
// // return 'string';
// // 2、如果抛出错误返回的结果是一个失败状态的Promise
// // throw new Error('error')
// // 3.返回的结果是一个Promise对象则返回值的Promise对象的状态与其一致
// return new Promise((resolve,reject)=>{
// // resolve('成功的数据');
// reject('失败了!');
// })
// }
// const result = fn()
// console.log(result);
// const p = new Promise((resolve,reject)=>{
// // resolve('successful');
// reject('error');
// });
// //await 要放在asnyc 函数里面
// async function fn(){
// try{
// //await表达式右侧是一个Promise对象返回值为promise对象的值
// let result = await p;
// console.log(result);
// }catch(e){
// console.log(e)
// }
// }
// fn()
//存在跨域问题
// readyState存有服务器响应的状态信息。
// 0: 请求未初始化
// 1: 服务器连接已建立
// 2: 请求已接收
// 3: 请求处理中
// 4: 请求已完成,且响应已就绪
// responseText获得字符串形式的响应数据。
function sendAjax(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open("GET", url);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status >= 200 && xhr.status < 300) {
resolve(xhr.response);
}else{
// xhr.statusText是浏览器的错误信息因为跨浏览器的时候可能不太一致不建议直接使用它
reject("数据返回失败!状态码" + xhr.status + "状态信息:" + xhr.statusText);
}
}
}
})
}
// 使用 promise的then方法
// sendAjax('./data/test.geojson').then(value=>{
// console.log(value);
// },reason=>{
// console.log(reason);
// })
// 使用async和await表达式
async function main(){
let result = await sendAjax('./data/jsonString.txt');
console.log(result)
}
main()
</script>
</body>
</html>