Promsie详解

148 阅读1分钟

为何诞生

Promise 解决的是异步编码风格的问题,而不是一些其他的问题,

异步编程的问题:代码逻辑不连续

image.png

image.png


//执行状态
function onResolve(response){console.log(response) }
function onReject(error){console.log(error) }

let xhr = new XMLHttpRequest()
xhr.ontimeout = function(e) { onReject(e)}
xhr.onerror = function(e) { onReject(e) }
xhr.onreadystatechange = function () { onResolve(xhr.response) }

//设置请求类型,请求URL,是否同步信息
let URL = 'https://time.geekbang.com'
xhr.open('Get', URL, true);

//设置参数
xhr.timeout = 3000 //设置xhr请求的超时时间
xhr.responseType = "text" //设置响应返回的数据格式
xhr.setRequestHeader("X_TEST","time.geekbang")

//发出请求
xhr.send();

image.png

封装异步代码,让处理流程变得线性

image.png

image.png

image.png

image.png

新的问题:回调地狱

image.png

image.png

Promise:消灭嵌套调用和多次错误处理

image.png

image.png

image.png

image.png

image.png

现在我们知道了 Promise 通过回调函数延迟绑定和回调函数返回值穿透的技术,解决了循环嵌套。