Promise

异步

ES6 原生提供了 Promise 对象。异步模式在web编程中变得越来越重要,但实际使用时会遇到大量异步回调的书写,造成编程的复杂性。因此JS库添加了Promise。有时也称之为deferred。

术语

Promise,就是一个对象,用来传递异步操作的消息。这种模式不会阻塞和等待长时间的操作完成,而是返回一个代表了承诺的(promised)结果的对象。
promise模式在任何时刻都处于以下三种状态之一:未完成(unfulfilled)、已完成(resolved)和拒绝(rejected)。使用如下:

function step1(resolve, reject) {
    console.log(typeof resolve);//function
    console.log(typeof reject);// function
    resolve("Step1 success");
}

new Promise(step1).then(function(val){
    console.info(val);//Step1 success
});
从上面可以看出,resolve和reject类型都是function。

状态变化

function step1(resolve, reject) {
    console.log(typeof resolve);//function
    console.log(typeof reject);// function
    resolve("Step1 success");
    reject("faild")
}

new Promise(step1).then(function(val){
    console.info(val);//Step1 success
}, function (val) {
    console.info(val);
})
这里让resolve和reject都执行,发现了吧。只能执行一个。而且执行reject后,then就不能正常执行了。这是因为promise的三种状态:未完成(unfulfilled)、已完成(resolved)和拒绝(rejected),一旦状态改变,就不会再变,之后任何时候都可以得到这个结果。

Then

一个 promise 必须提供一个 then 方法以访问其当前值、终值和原因.promise 的 then 方法接受两个参数:

promise.then(onFulfilled, onRejected)
参数可选,resolve时,onFulfilled被调用。 reject时,onRejected被调用。
另外,then可以连续多个,即我们可以链式调用,promise.then().then().then()。

Then的返回值

API中解释如下
Description
As the then and Promise.prototype.catch() methods return promises, they can be chained — an operation called composition.
也就是说then方法返回的还是一个promise对象,因此我们能够进行对其进行链式调用的原因。

例子

var val = 1;

function step1(resolve, reject) {
	console.log("step1 exe");
	if (val>=1) {
		// console.log(typeof resolve)
		resolve(function(){
			val++;
			return val;
		});
	} else if(val ==0) {
		reject(val);
	}
}

function step2(resolve, reject) {
	console.log("step2 exe");
	if (val>=1) {
		// console.log(typeof resolve)
		resolve("hello I am second");
	} else if(val ==0) {
		reject(val);
	}
}

function step3(resolve, reject) {
	console.log("step3 exe");
	if (val>=1) {
		// console.log(typeof resolve)
		// console.log(this.status)
		resolve("hello I am third");
	} else if(val ==0) {
		reject("step3 reject");
	}
}

new Promise(step1).then(function(val){
	console.log("Exe step1 then");
	console.info(val())
	// console.log(this.status)
	return new Promise(step2);
}).then(function(val){
	console.log("");
	console.log("Exe step2 then");
	console.info(val)
	return new Promise(step3);
}).then(function(val){
	console.log("");
	console.log("Exe step3 then");
	console.log( val)
	console.info(val)
	return val;
}).then(function(val){
	console.log("");
	console.log("Exe step3 then last");
	console.info(val)
	console.info(val)
	return val;
}).then(function() {
	console.log("end")
});


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值