Promise 是异步编程的一种解决方案。react
/** * 属性 */ Promise.length Promise.prototype /** * 方法 */ Promise.all(iterable) // 全部成功触发成功 任何失败触发失败 Promise.race(iterable) // 任意一个成功或失败后触发 Promise.reject(reason) Promise.resolve(value) /** * 原型 */ Promise.prototype.constructor //方法 Promise.prototype.catch(onRejected) Promise.prototype.then(onFulfilled, onRejected) Promise.prototype.finally(onFinally)
Promise 有三种状态编程
pending 是初始状态,执行 resolve/reject 会进入对应状态,若是不执行,责一直为 pending 状态跨域
例以下面代码,promise 将一直在 pending 状态,不会执行 then/catch.promise
new Promise(function (resolve, reject) { }) .then(res => console.log(res)) .catch(err => console.log(err))
resolve 意味着操做成功完成, 若是有 .then,值会传入 .then 的第一个参数函数里。浏览器
如网络
new Promise(function (resolve, reject) { resolve(1) }) .then(res => console.log(res))
then 的第一个参数是成功的回调,第一个参数的返回值会影响接下来链的去向。第一个参数的返回值通常有三种状况数据结构
例如想要在当前 then 终止,能够这样操做:异步
.then((res) => new Promise(() => {}))
reject 意味着操做失败。异步编程
使用 .catch 会捕获到错误信息。函数
与代码报错(如 undefined.a)不一样的是, 代码报错若是不使用 catch 捕获,会向外传递,最终传递到根结点;而 reject 属于 promise 错误,即便不使用 catch 捕获也不会对全局有影响。
先来看几个问题:
带着这几个问题,来看看 fetch。
fetch 返回值是 promise,因此有三种状态 pending、resolve、reject.
咱们还发现,请求失败时,只能 catch 到最后一行错误, 如图
捕获后
实现有几个难点,
试了下,Promise.reject('xxx') 这样的报错方式虽然是微观任务,可是老是在.then以后才在控制台输出,更像是宏观任务。因此也加个setTImeout宏观任务调至后面。
var fetch = function () { return new Promise(function (resolve, reject) { setTimeout(function () { if ('请求成功 200') { resolve('Response数据结构'); } else if ('请求成功 404,500等') { Promise.reject('GET xxxxxxxx 404'); setTimeout(function () { resolve('Response数据结构'); }); } }) }) }
一样加个 setTimeout
var fetch = function () { return new Promise(function (resolve, reject) { setTimeout(function () { if ('请求成功 200') { resolve('Response数据结构'); } else if ('请求成功 404,500等') { Promise.reject('GET xxxxxxxx 404'); setTimeout(function () { resolve('Response数据结构'); }); } else if ('请求失败') { Promise.reject('Access to fetch xxxxx with CORS disabled.'); Promise.reject('GET xxxxx net::ERR_FAILED'); setTimeout(function () { reject('TypeError: Failed to fetch'); }); } }) }) }
仍是有些问题,咱们实现的由于在promise 中,错误会有前缀 Uncaught (in promise)。浏览器客户端应该有更好的实现方式。
最后总结一下 fetch 的三种状况
抛错均不影响代码执行,与 undefined.a 不一样。