慕课笔记--[课程]进击Node.js基础(二)

来源:互联网 发布:手机怎么找到淘宝客服 编辑:程序博客网 时间:2024/05/22 00:18

一、Promise简介

2015年发布了ES6标准,所谓 Promise,就是ES6标准的一个对象,用来传递异步操作的消息。它代表了某个未来才会知道结果的事件(通常是一个异步操作),并且这个事件提供统一的 API,可供进一步处理。有了 Promise 对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数。此外,Promise 对象提供统一的接口,使得控制异步操作更加容易。var promise = new Promise(function(resolve, reject) { if (/* 异步操作成功 */){ resolve(value); } else { reject(error); }});promise.then(function(value) { // success}, function(value) { // failure});Promise函数接受一个函数作为参数,该函数的两个参数分别是 resolve 方法和 reject 方法。如果异步操作成功,则用 resolve 方法将 Promise 对象的状态,从「未完成」变为「成功」(即从 pending 变为 resolved);如果异步操作失败,则用 reject 方法将 Promise 对象的状态,从「未完成」变为「失败」(即从 pending 变为 rejected)。
完整示例源码:

<!DOCTYPE html>
<html>
<head>
<title>Promise animation</title>
<style type="text/css" media="screen">
.ball{
width: 40px;
height: 40px;
border-radius: 20px;
}
.ball1{
background: red;
}
.ball2{
background: yellow;
}
.ball3{
background: green;
}
</style>
<script type="text/javascript" src="./node_modules/bluebird/js/browser/bluebird.js"></script>
</head>
<body>
<div class="ball ball1" style="margin-left: 0"></div>
<div class="ball ball2" style="margin-left: 0"></div>
<div class="ball ball3" style="margin-left: 0"></div>
<script>
var ball1 = document.querySelector('.ball1');
var ball2 = document.querySelector('.ball2');
var ball3 = document.querySelector('.ball3');

// 方法一:常规回调函数
// function animate(ball, distance, cb){
// setTimeout(function(){
// var marginLeft = parseInt(ball.style.marginLeft, 10);
// if(marginLeft === distance){
// cb && cb();
// }else{
// if(marginLeft < distance){
// marginLeft++;
// }else{
// marginLeft--;
// }
// ball.style.marginLeft = marginLeft + 'px';
// animate(ball, distance, cb);
// }

// }, 13)
// }

// animate(ball1, 100, function(){
// animate(ball2, 200, function(){
// animate(ball3, 300, function(){
// animate(ball3, 150, function(){
// animate(ball2, 150, function(){
// animate(ball1, 150, function(){

// })
// })
// })
// })
// })
// })

// 方法二:promise
var Promise = window.Promise;

function promiseAnimate(ball, distance){
return new Promise(function(resolve, reject){

function _animate(){
setTimeout(function(){
var marginLeft = parseInt(ball.style.marginLeft, 10);

if(marginLeft === distance){
resolve();
}else{
if(marginLeft < distance){
marginLeft++;
}else{
marginLeft--;
}
ball.style.marginLeft = marginLeft + 'px';
_animate();
}

}, 13)
}
_animate();
});
}
promiseAnimate(ball1, 100)
.then(function(){
return promiseAnimate(ball2, 200);
})
.then(function(){
return promiseAnimate(ball3, 300);
})
.then(function(){
return promiseAnimate(ball3, 150);
})
.then(function(){
return promiseAnimate(ball2, 150);
})
.then(function(){
return promiseAnimate(ball1, 150);
})
</script>
</body>
</html>

二、Promise相关的知识

(一)Promise1. ES6的Promise语言标准2. Promise/A+规范(二)Promise使用场景1. 是一种异步的实践方案2. 特别是Callback Hell, 可以用同步的方式写异步代码(三) Promise的三种状态1. pending  未完成2. fulfilled 已完成3. rejected 失败(1->2, 1->3 正确)(2->1, 3->1, 2->3 错误)总结: 只能又未完成变为已完成或失败, 且不可逆, 改变只能一次, 不存在即已完成同事失败
(四)、实现异步的方式:1-callback 回调方式2-事件机制(监听+触发)【订阅者观察者】模式3-promise:表示一个异步操作的最终结果,以同步的方式来写代码,执行的操作是异步的,但是保证程序的执行顺序是同步的。
(五)、then方法必须返回一个Promise对象;then方法的第一个参数是上一个执行返回的结果

三、node.js的HTTP的net模块  buffer

1、buffer是一个构造函数同时也是一个对象

Buffer在nodejs中用来处理二进制的数组(js字符串是用utf-8存储的,处理二进制的能力是很弱的,而网络层对资源的请求,响应等基本以二进制来进行交互)创建一个专门存储二进制的缓存区,并提供了一些方法对这些缓存区的数据做进一步的处理buffer在nodejs里可全局访问buffer实例化(1)、 new Buffer('hello 你好');//以默认编码格式utf-8进行字符转换(2)、new Buffer('hello 你好','base64');//将默认编码格式修改为base64(3)、var buf = new Buffer(8);//设置缓存区的大小   buf.length; //8(4)、var buf = new Buffer('12345678');   console.log(buf) //buf长度为8(5)、var buf = new Buffer(7);   buf.write('12345678');   console.log(buf) //只要指定了buf长度,超出了都不会被缓存(6)、var buf = new Buffer([1,2,3,4]);//经过数组初始化   console.log(buf[1])//值为2. 可以通过下标来访问,如果值为小数,会直接取整数。
2、Buffer的实例化分为三种方法
(1)、通过字符串的形式实例化,eg:new Buffer('hello world');
(2)、通过定义buffer中size的大小实例化,eg:var buf=new Buffer(8)//定义一个缓冲区长度8的;
(3)、通过数组的方式实例化,eg:var buf=new Buffer([1,2,3,4])。
3、Buffer的属性与方法
poolSize:内存载体的容量isBuffer:是否为buffer类型对象compare:用来判断两个buffer对象的相对位置isEncoding:判断nodejs是否支持某种编码concat:将几个buffer对象连接创建一个新的buffer对象byteLength:获得指定编码下字符串所占的字节数
三、node.js的HTTP的net模块  buffer

var fs = require('fs');
var readStream = fs.createReadStream('test.mp4');
var writeStream = fs.createWriteStream('write.mp4');
readStream.on('data',function(chuck){
   if(writeSream.write(chunk)===false){//判断是否将数据写出缓存区,如果是false暂停读取
        readStream.puse();                                  
   }

});
readStream.on('end',function(){
    console.log('读取完成');
   writeStream.end();
});
writeStream.on('drain',function(){
   readStream.resume();//开始读
});