揭开Promise的神秘面纱!(一)

120 阅读2分钟

| 前言

回调函数可以说是所有异步编程方案的根基

但是当遇到一些复杂的异步流程时直接使用传统回调方式去完成

无法避免会遇到大量的函数嵌套造成回调地狱问题。

在此背景下,CommonJS社区提出了Promise的规范,目的就是为异步编程提供一种更合理的、更统一的解决方案,后来被纳入了ES2015标准中

| Promise初识

Promis实际上是一个对象,用来表示一个异步任务结束后,它是成功还是失败,并执行相对应的回调

基本用法:

Promise会对外做出一个承诺,这个承诺可能成功也可能失败,承诺达成会执行相对应的回调,且这个承诺有且仅能为其中的一种状态

const promise = new Promise((resolve, reject) {
	// 这里兑换承诺
	resolve(100)  // 承诺达成  奖励100元
	// reject(new Error('promise rejected'))   // 承诺失败
})

promise.then(frunction(value) {
	console.log('resolved', value)
}, function(error) {
	console.log('rejected', error)
})

使用案例:

// 封装AJAX请求
function ajax(url) {
	return new Promise(function(resolve, reject) {
		var xhr = new XMLHttpRequest()
		xhr.open('GET', url)
		xhr.responseType = 'json'
		xhr.onload = function() {
			if(this.status === 200) {
				resolve(this.response)                // 将承诺的状态改为成功并将数据返回
			} else {
				reject(new Error(this.statusText))   //  将承诺的状态改为失败并将失败原因返回
			}
		}
		xhr.send()
	})
}

ajax('/api/admin/getPage').then(function(res) {
	console.log(res)      // 接收成功的数据
}, function(error) {
	console.log(error)   // 接收失败的原因
})

promise的链式调用:

在此之前让我们先明确几个要点

  • Promise的then方法会返回一个全新的promise对象
  • 每个then方法都是在为上一个then返回的promise对象添加状态明确后的回调
  • 前一个then方法的返回值会作为后一个then方法回调的参数
例:
ajax('/api/admin/getPage')
	.then(function(value) {
		console.log('111')
		return ajax('/api/admin/getPage')
	})
	.then(function(value) {
		console.log('222')
		console.log(value)    // 这里会接收到上一个then方法return的结果 也就是ajax返回的数据
		return ’test‘
	})
	.then(function(value) {
		console.log('333')
		console.log(value)   // ’test'
	})

| 写在最后...

一定要爱着点什么, 它让我们变得坚韧、宽容、充盈。

业余的,爱着。