Map&Promise

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>ES6</title>
    <script type="text/javascript" src="js/jquery.min.js"></script>
	<script type="text/javascript" src="promise.js"></script>
  </head>
  <body>
  <button>click</button>
  <script type="text/javascript">
      //Map   键值对 类似对象 传统对象只能用字符串当作键名,Map的键可以是其它的类型
	  var m = new Map();
		m.set('a','a').set('b','b');
		var a={name:'hello'};
		m.set(a,'name');
		m//
		.get()
		.has()
		.delete()
		.clear()
		.size
		
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		for(let key of m1.keys()){
			console.log(key);
		}
		
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		for(let key of m1.values()){
			console.log(key);
		}
		
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		for(let [k,v] of m1){
			console.log(k,v);
		}
		
		//扩展运算符
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		var s = [...m1.keys()];  //a,b,c	

		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		var s = [...m1.values()];  //123
		
		//与其它结构转换
		//1\MAP转为数组
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		//[...m1.keys()];   
		//[...m1.values()]; 
		//[...m1];
		//2、数组转为map
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		var s = [...m1];
		//var m2 = new Map([...m1]);
		var m2 = new Map(s);
		m2.size
		//3、转为对象
		var m1 = new Map([['a','1'],['b','2'],['c','3']]);
		var o ={};
		for (let [k,v] of m1){
			o[k] =v;
		};
		console.log(o);
		
		
		//promise   优化AJAX  三种状态(进行中,已完成,已失败)  </script>
  </body>
</html>
const getJSON = function(url,type,data) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      };
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open(type, url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    if(type=='get'){
      client.send();
    }else {
      client.setRequestHeader("Content-Type","application/json");//data只能是JSON字符串
      client.send(JSON.stringify(data))  //post请求传入string
    }
  
  });
  return promise;
};

$(function() {
	$("button").click(function() {	
		getJSON('http://localhost:3000/info','get')
    .then(function(json) {
		//success
		console.log('ok');
    })
    .catch(function(error) {
		  console.error('出错了', error);
		});
	});
  //JQUERY 1.5.0返回的是xhr对象  高于1.5.0返回的deferred对象
})
<!DOCTYPE>
 <html lang="zh-en">
 <head>
     <title>js实现简单留言板</title>
     <meta http-equiv="content-type" content="text/html;charset=utf-8">
     <script src="js/jquery-1.11.0.min.js"></script>
     <script type="text/javascript" src="js/ajax_then.js"></script>
     <link href="css/bootstrap.min.css" rel="stylesheet"/>
     <link href="css/demo.css" rel="stylesheet"/> 
 </head> 
 <body>
     <div class="container">
        <div class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-1 control-label">昵称:</label>
                <div class="col-sm-11">
                    <input type="email" class="form-control name" id="inputEmail3" placeholder="请输入昵称">
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-1 control-label">留言:</label>
                <div class="col-sm-11">
                    <textarea class="form-control message" rows="5" placeholder="请输入内容"></textarea>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-offset-1 col-sm-11">
                    <button type="submit" class="btn btn-success submit">添加留言</button>
                    <button class="btn btn-success queryThen">串行</button>
                    <button class="btn btn-success queryWhen">并行</button>
                </div>
            </div>
        </div>

        <div class="panel panel-primary">
            <div class="panel-heading">留言列表</div>
                <div class="panel-body">
                    <ul class="list-group messageList">
                        <!-- <li class="list-group-item">张三
                            <span>说:</span>大家好!
                        </li> -->
                    </ul>
                </div>
        </div>
    </div>
</body>
</html>
/**
Simple Server for web api test.
*/
/**Connect是一个node中间件(middleware)框架。
如果把一个http处理过程比作是污水处理,中间件就像是一层层的过滤网。
每个中间件在http处理过程中通过改写request或(和)response的数据、状态,实现了特定的功能。
中间件就是类似于一个过滤器的东西,在客户端和应用程序之间的一个处理请求和响应的的方法。*/

var connect = require('connect');  //创建连接
var bodyParser = require('body-parser');   //body解析

var app = connect()
    .use(bodyParser.json())   //JSON解析
    .use(bodyParser.urlencoded({extended: true}))
	//use()方法还有一个可选的路径字符串,对传入请求的URL的开始匹配。
	//use方法来维护一个中间件队列
	.use(function (req, res, next) {
		//跨域处理
		// Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');  //允许任何源
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  //允许任何方法
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');   //允许任何类型
		res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});    //utf-8转码
		next();  //next 方法就是一个递归调用
	})
	.use('/add', function(req, res, next) {
		console.log(req.body);
		var data = [];
		data.push(req.body);
		console.log(data);
		res.end(JSON.stringify(data));
		next();
	})
	.use('/map/add1', function(req, res, next) {
		var data={
			"code": "200",
			"msg": "success",
			"result": {
				"id":1,
			}
		};
		res.end(JSON.stringify(data));
		next();      //
	})
	.use('/map/add2', function(req, res, next) {
		var data={
			"code": "200",
			"msg": "success",
			"result": {
				"name": "sonia",
				"content": "广告投放1"
			}
		};
		res.end(JSON.stringify(data));
		next();      //
	})
    .listen(3000);
console.log('Server started on port 3000.');
const getJSON = function(url,type, data) {
  const promise = new Promise(function(resolve, reject){
    const handler = function() {
      if (this.readyState !== 4) {
        return;
      };
      if (this.status === 200) {
        resolve(this.response);
      } else {
        reject(new Error(this.statusText));
      }
    };
    const client = new XMLHttpRequest();
    client.open(type, url);
    client.onreadystatechange = handler;
    client.responseType = "json";
    if(type =='get'){
    	client.send();
    }else {
    	client.setRequestHeader("Content-Type", "application/json");
    	client.send(JSON.stringify(data));
    }
  });
  return promise;
};

$(function() {
	//添加数据
	$(".submit").click(() => {
		let _name = $(".name").val(),
			_message = $(".message").val();
		if(_name =='' || _message =='') {
			alert('请输入信息!');
			return false;
		}
		$(".name,.message").val("");
		add(_name,_message);
	});
	let add = (name, message) => {
		getJSON("http:localhost:3000/add",'post', {name: name, message: message})
		.then(function(json) {
			for (let i=0; i<json.length; i++) {
				$(".messageList").append(`<li class="list-group-item"><span class="key">${json[i].name}</span><span>说:</span><span class="value">${json[i].message}</span>
			    </li>`);
			}
		}, function(error) {
		  console.error('出错了', error);
		});
	};

	//列表显示
	let  listShow = () => {
		//原生promise
		/*getJSON("/map/get",'get').then(function(d) {
			_showList(d);
		}, function(error) {
		  console.error('出错了', error);
		});*/

		//$.ajax() 低于1.5.0版本的jQuery,返回的是XHR对象,高于1.5.0版本,返回的是deferred对象,可以进行链式操作。
		// 链式写法
		let list = $(".messageList"),str = "";
		$.ajax({url:"http:localhost:3000/map/get",dataType:"json",type:"get"})
	  .done(function(d){
			
			})
	  .fail(function(){ alert("出错啦!"); });
	};

	//查询数据
	//链式写法  串行
	$(".queryThen").click(()=> queryThen());
	let queryThen = ()=> {
		$.ajax({url:"http:localhost:3000/map/add1",dataType:"json",type:"get"})
	  .then(data => {
				return $.ajax({url:"http:localhost:3000/map/add2",dataType:"json",type:"post",data:{id:data.result.id}})
			 //return $.get("http:localhost:3000/map/add2", data.result.id);
			})
	    .then(data => {
				alert(data);
			})
			.catch(error=>{
				console.log(error);
			})
	};

	let addPromise1 = new Promise((resolve,reject) => {
		getJSON("http:localhost:3000/map/add1",'get').then(function(d) {
			resolve(d);
		}, function(error) {
		  console.error('出错了', error);
		});
	});
	let addPromise2 = new Promise((resolve,reject) => {
		getJSON("http:localhost:3000/map/add2",'get').then(function(d) {
			resolve(d);
		}, function(error) {
		  console.error('出错了', error);
		});
	});
	// 并行  when 多个请求完成后返回
	$(".queryWhen").click(()=> queryWhen());
	let queryWhen = ()=> {
		/*$.when($.ajax({url:"/map/add1",dataType:"json",type:"get"}), $.ajax({url:"/map/add2",dataType:"json",type:"get"}))
		.then((data1,data2) => {
			console.log(data1[0]);
			console.log(data2[0]);
		}, () => { alert("出错啦!"); });*/

		Promise.all([
		  addPromise1,
		  addPromise2
		]).then(([add1,add2])=>{
			console.log(add1);
			console.log(add2);
		}, function(error) {
		  console.error('出错了', error);
		});
	};
})
posted @ 2021-03-05 10:42  德乌姆列特  阅读(137)  评论(0编辑  收藏  举报