首先用最简单的方式实现一个动画效果

<!doctype>
<html>
<head>
<title>Promise animation</title>
<style type="text/css">
.ball {
width: 40px;
height: 40px;
border-radius: 20px;
} .ball1 {
background: red;
}
.ball2 {
background: yellow;
}
.ball3 {
background: green;
} </style>
</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 type="text/javascript">
//定义三个球
var ball1 = document.querySelector('.ball1')
var ball2 = document.querySelector('.ball2')
var ball3 = document.querySelector('.ball3')
//球,移动距离,回调函数
function animate(ball, distance, cd){
//每13毫秒改变一次圆球的位置,直到到达指定位置
setTimeout(function(){
var marginLeft = parseInt(ball.style.marginLeft,10)
//球达到预期位置
if(marginLeft === distance){
cd && cd()
}else{
//球在左侧
if(marginLeft < distance){
marginLeft++
}else{
//球在右侧
marginLeft--
}
//调整球的位置
ball.style.marginLeft = marginLeft
animate(ball, distance, cd)
}
},13)
}
//控制动画
animate(ball1, 100,function(){
animate(ball2, 200, function(){
animate(ball3, 150, function(){
animate(ball2, 150, function(){
animate(ball1, 150, function(){ })
})
})
})
}) </script>
</body>
</html>

使用promise实现相同功能

<!doctype>
<html>
<head>
<title>Promise animation</title>
<style type="text/css">
.ball {
width: 40px;
height: 40px;
border-radius: 20px;
} .ball1 {
background: red;
}
.ball2 {
background: yellow;
}
.ball3 {
background: green;
}
</style> <script src="./node_modules/bluebird/js/browser/bluebird.js" type="text/javascript"></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 type="text/javascript">
//定义三个球
var ball1 = document.querySelector('.ball1')
var ball2 = document.querySelector('.ball2')
var ball3 = document.querySelector('.ball3') var Promise = window.Promise function promiseAnimate(ball, distance){
return new Promise(function(resolve, reject){
//球,移动距离,回调函数
function _animate(){
//每13毫秒改变一次圆球的位置,直到到达指定位置
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, 150)
})
.then(function(){
return promiseAnimate(ball2, 150)
})
.then(function(){
return promiseAnimate(ball1, 150)
})
</script>
</body>
</html>

promise对象三种状态:

  • -未完成(pending)
  • -已完成(fulfiled)
  • -失败(rejected)

promiseA与promiseA+不同点:

  • -A+规范通过属于thenable来区分promise对象
  • -A+定义onFulfilled/onRejected必须是作为函数来调用,而且调用过程必须是异步的
  • -A+严格定义了then方法链式调用时onFulfilled/onRejected的调用顺序

promise then 方法

将异步执行的回调函数放入then方法中,规范链式书写

promiseObj.then(onFunction, onRejected)

onFulfilled = function(value){
return promiseObj2
} onRejected = function(err){}

promise库有很多

  • bluebird
  • Q
  • then.js
  • es6-promise
  • ypromise
  • async
  • native-promise-only

使用promise重写爬虫

对比:07慕课网《进击Node.js基础(一)》HTTP小爬虫

var http = require('http')
var Promise = require('bluebird')
var cheerio = require('cheerio') //使用模块
var baseUrl = 'http://www.imooc.com/learn/'
var videoIds = [728,637,348] function filterChapters(html){
//可以像jQuery一样使用
var $ = cheerio.load(html) var chapters = $('.chapter')
var title = $('.clearfix h2').text()
var number = $('.js-learn-num').text() // courseData = {
// title : title,
// number : 0,
// videos : [{
// chapterTitle:'',
// videos:[{
// title:'',
// id:''
// }]
// } var courseData = {
title : title,
number : number,
videos : []
} chapters.each(function(item){
var chapter = $(this)
var chapterTitle = chapter.find('h3').text()
var videos = chapter.find('.video').children('li')
var chapterData = {
chapterTitle :chapterTitle.trim(),
videos:[]
} videos.each(function(item){
var video = $(this).find('a')
var videoTile = video.text()
var id = video.attr('href').split('video/')[1]
chapterData.videos.push({
title: videoTile.trim(),
id : id
})
})
courseData.videos.push(chapterData) })
return courseData
} function printCourseInfo(coursesData){ coursesData.forEach(function(courseData){
console.log(courseData.number + ' 人学过 ' + courseData.title + '\n')
})
coursesData.forEach(function(courseData){
console.log('###' + courseData.title + '\n')
courseData.videos.forEach(function(item){
var chapterTitle = item.chapterTitle item.videos.forEach(function(video){
console.log(' 【' + video.id + '】' + video.title + '\n')
})
}) })
} function getPageAsync(url){
return new Promise(function(resolve,reject){
console.log('正则爬取'+ url) http.get(url,function(res){
var html = '' res.on('data',function(data){
html += data
}) res.on('end',function(){
resolve(html) //var courseData = filterChapters(html)
//printCourseInfo(courseData)
})
}).on('errer',function(e){
reject(e)
//console.log('出错')
}) })
} var fetchCourseArray = []
videoIds.forEach(function(id){
fetchCourseArray.push(getPageAsync(baseUrl + id))
}) Promise
.all(fetchCourseArray)
.then(function(pages){
//对多个数据处理
var coursesData = [] pages.forEach(function(html){
var curses = filterChapters(html)
coursesData.push(curses)
}) coursesData.sort(function(a,b){
return a.number < b.number
}) printCourseInfo(coursesData)
})

HTTP和HTTPS

HTTPS在http的基础上进行了加密

运行HTTPS服务,.pem文件还需要另外的方式创建

var https = require('https')
var fs = require('fs') var options = {
key: fs.readFileSync('ssh_key.pem'),//ssl 文件
key: fs.readFileSync('ssh_cert.pem'),//证书文件 } //运行HTTPS服务器
https.createServer(options, function(req,res){
res.writeHead(200)
res.end('hello world'+ req)
}).listen(8090)

10慕课网《进击Node.js基础(一)》初识promise的更多相关文章

  1. 01慕课网《进击Node.js基础(一)》Node.js安装,创建例子

    版本:偶数位为稳定版本,基数为非稳定版本 - 0.6.x - 0.7.x    - 0.8.x -0.9.x    -0.10.x  -0.11.x 概念:Node.js采用谷歌浏览器的V8引擎,用C ...

  2. 03慕课网《进击Node.js基础(一)》API-URL网址解析

    url url.parse(url,query,host);解析域名 url必须,地址字符串 query可选 host 可选:在不清楚协议时正确解析 querystring 字符串和对象之间互相解析 ...

  3. 07慕课网《进击Node.js基础(一)》HTTP小爬虫

    获取HTML页面 var http = require('http') var url='http://www.imooc.com/learn/348' http.get(url,function(r ...

  4. 进击Node.js基础(二)

    一.一个牛逼闪闪的知识点Promise npm install bluebird 二.Promise实例 ball.html <!doctype> <!DOCTYPE html> ...

  5. 02慕课网《进击Node.js基础(一)》——CommonJs标准

    是一套规范管理模块 每个js 为一个模块,多个模块作为一个包 node.js和Couchdb是对其的实现: 不同于jQuery 模块:定义.标识.引用(地址/模块名称) 模块类型: 核心模块http ...

  6. 进击Node.js基础(一)

    一.前言 1:Node.js本质上是用chrome浏览器 v8引擎 使用c++编写的JS运行环境 2:相比于JS没有浏览器安全级的限制,额外提供了一些系统级的API:文件读写,进程管理,网络通信等. ...

  7. 11慕课网《进击Node.js基础(一)》Buffer和Stream

    Buffer 用来保存原始数据 (logo.png) 以下代码读取logo.png为buffer类型 然后将buffer转化为string,新建png 可以将字符串配置: data:image/png ...

  8. 09慕课网《进击Node.js基础(一)》HTTP-get/request

    get是对request封装 可以在后台发起http请求,获取远程资源,更新或者同步远程资源 http.request(options[,callback]) 以下代码灌水失败: var http = ...

  9. 08慕课网《进击Node.js基础(一)》事件events

    引用events模块中的EventEmitter 事件的监听和发射 相同的事件发射数量有限,可以通过setMaxListeners设置峰值 var EventEmitter = require('ev ...

随机推荐

  1. Alpha冲刺&总结报告(12/12)(麻瓜制造者)

    各个成员今日完成的任务 邓弘立: 完成了上传头像的功能 符天愉: 对所有接口进行了再次测试 江郑: 完成了发布需求接口部分的进一步测试和接口文档的编写 刘双玉: 完成了商品信息接口部分的进一步测试和接 ...

  2. Breaking Down Type Erasure in Swift

    Type Erasure Pattern We can use the type erasure pattern to combine both generic type parameters and ...

  3. swift protocol的几种形式

    三个关注点:1.形式:2.实现方式:3.使用方式: 一.基本形式: 形式:内部无泛型类型: 实现:只需指定类型和实现相应的功能即可: 使用:可以用在其他类型出现的任何地方: protocol Resp ...

  4. nowcoder练习赛28

    https://www.nowcoder.com/acm/contest/200#question 最近突然找到了打比赛的乐趣,于是参加了这场比赛. 生日宴会:https://www.nowcoder ...

  5. BZOJ3534:[SDOI2014]重建(矩阵树定理)

    Description T国有N个城市,用若干双向道路连接.一对城市之间至多存在一条道路. 在一次洪水之后,一些道路受损无法通行.虽然已经有人开始调查道路的损毁情况,但直到现在几乎没有消息传回. 幸运 ...

  6. [JLOI2013]删除物品

    嘟嘟嘟 只要每一次将优先级最高的上面的物品移走,就一定能保证是最优解. 所以我们只要想办法简化这个模拟移物品的过程,看完了题解后,发现可以这么想,我们可以把两个栈头碰头的挨在一起,然后设一个指针代表两 ...

  7. 8、JVM--虚拟机字节码执行引擎

    8.1.概述 执行引擎是Java虚拟机最核心的组成部分之一.“虚拟机”是一个相对于“物理机”的概念,这两种机器都有代码执行能力,其区别是物理机的执行引擎是直接建立在处理器.硬件.指令集和操作系统层面上 ...

  8. Springmvc常见问题

    问题一:org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userCont ...

  9. VC++ MFC单文档应用程序SDI下调用glGenBuffersARB(1, &pbo)方法编译通过但执行时出错原因分析及解决办法:glewInit()初始化的错误

    1.问题症状 在VC++环境下,利用MFC单文档应用程序SDI下开发OpenGL程序,当调用glGenBuffersARB(1, &pbo)方法编译通过但执行时出错,出错代码如下: OpenG ...

  10. Oracle 表删除操作

    删除表内容(dml):delete from 删除表结构(ddl):drop table xx 清空表(ddl):truncate table 清空整张表,不能回滚,不会产生大量日志文件: 表空间会得 ...