玩玩 ES6 的 Promise 功能

Promise 是一个 Object, 它有两种形式:

1. Promise.resolve()
这样直接可以用.

2.new Promise(function(resolved,rejected){ … resolved(param) … })
一个 Object 的形式, 里面要有一个 function.


var count = 0;
var tick = () => {
	count++;
	setTimeout(() => {
		process.stdout.write('.');
		if(count < 100) tick();
	},100);
}
tick();//Init


//Promise Syntax Tricks
Promise.resolve()
	.then(() => {console.log('1')})
	.then(() => {
		return new Promise( (resolved,rejected) =>
			setTimeout(() => {
				console.log('2')
				resolved()
			},2000)
		);
	})
	.then(() => {console.log('3')})
	.then(() => {
		return new Promise( (resolved,rejected) =>
			setTimeout(() => {
				console.log('4')
				resolved()
			},4000)
		);
	})
	.then(() => {
		//Block without promise
		setTimeout(() => {
			console.log('5')
		},1000)
	})
	.then(() => {console.log('6')})
	.then(() => {console.log('7')})
	.then(() => {console.log('8')})

//Kinda messy, isn't it?	

Output:


node index.js
1
...................2
3
........................................4
6
7
8
..........5
...............................