$.get(url,(data) => {
console.log(data)
)
$.get(url,data1 => { console.log(data1) $.get(data1.url,data2 => { console.log(data1) }) })
const request = url => { return new Promise((resolve,reject) => { $.get(url,data => { resolve(data) }); }) }; // 请求data1 request(url).then(data1 => { return request(data1.url); }).then(data2 => request(data2.url); }).then(data3 => { console.log(data3); }).catch(err => throw new Error(err));
import axios from 'axios'; axios.get(url).then(data => { console.log(data) })
const promise = { 异步处理 处理结束后、调用resolve 或 reject });
onFulfilled 是用来接收promise成功的值 // onRejected 是用来接收promise失败的原因 promise.then(onFulfilled,onRejected);
const promise = { resolve('fulfilled'); 状态由 pending => fulfilled }); promise.then(result => { onFulfilled console.log(result); 'fulfilled' },reason => { onRejected 不会被调用 })
const promise = { reject('rejected'); 状态由 pending => rejected onFulfilled 不会被调用 },reason => { onRejected console.log(rejected); 'rejected' })
romise.catch(onRejected) 相当于 promise.then(null,onRrejected); 注意 onRejected 不能捕获当前onFulfilled中的异常 promise.then(onFulfilled,onRrejected); 可以写成: promise.then(onFulfilled) .catch(onRrejected);
function taskA() { console.log("Task A"); } taskB() { console.log("Task B" onRejected(error) { console.log("Catch Error: A or B"var promise = Promise.resolve(); promise .then(taskA) .then(taskB) .catch(onRejected) 捕获前面then方法中的异常
Promise.resolve('hello').then((value){ console.log(value); }); Promise.resolve('hello'); 相当于 const promise = new Promise(resolve => { resolve('hello'); });
Promise.reject(24 { reject(24); });
const p1 = { resolve(1); }); const p2 = { resolve(2); }); const p3 = { reject(3); }); Promise.all([p1,p2,p3]).then(data => { console.log(data); [1,2,3] 结果顺序和promise实例数组顺序是一致的 },err => { console.log(err); });
timerPromisefy(delay) { new Promise( (resolve,reject) { setTimeout( () { resolve(delay); },delay); }); } var startDate = Date.now(); Promise.race([ timerPromisefy(10),timerPromisefy(20) ]).then( (values) { console.log(values); 10 });
/** * Promise 实现 遵循promise/A+规范 * Promise/A+规范译文: * https://malcolmyu.github.io/2015/06/12/Promises-A-Plus/#note-4 */ promise 三个状态 const PENDING = "pending"; const FULFILLED = "fulfilled"; const REJECTED = "rejected"; Promise(excutor) { let that = this; 缓存当前promise实例对象 that.status = PENDING; 初始状态 that.value = undefined; fulfilled状态时 返回的信息 that.reason = undefined; rejected状态时 拒绝的原因 that.onFulfilledCallbacks = []; 存储fulfilled状态对应的onFulfilled函数 that.onRejectedCallbacks = []; 存储rejected状态对应的onRejected函数 function resolve(value) { value成功态时接收的终值 if(value instanceof Promise) { value.then(resolve,reject); } 为什么resolve 加setTimeout? 2.2.4规范 onFulfilled 和 onRejected 只允许在 execution context 栈仅包含平台代码时运行. 注1 这里的平台代码指的是引擎、环境以及 promise 的实施代码。实践中要确保 onFulfilled 和 onRejected 方法异步执行,且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行。 setTimeout(() => { 调用resolve 回调对应onFulfilled函数 if (that.status === PENDING) { 只能由pedning状态 => fulfilled状态 (避免调用多次resolve reject) that.status = FULFILLED; that.value = value; that.onFulfilledCallbacks.forEach(cb => cb(that.value)); } }); } function reject(reason) { reason失败态时接收的拒因 setTimeout(() => 调用reject 回调对应onRejected函数 只能由pedning状态 => rejected状态 (避免调用多次resolve reject) that.status = REJECTED; that.reason = reason; that.onRejectedCallbacks.forEach(cb => cb(that.reason)); } }); } 捕获在excutor执行器中抛出的异常 new Promise((resolve,reject) => { throw new Error('error in excutor') }) try { excutor(resolve,reject); } (e) { reject(e); } } * * resolve中的值几种情况: * 1.普通值 * 2.promise对象 * 3.thenable对象/函数 * * 对resolve 进行改造增强 针对resolve中不同值情况 进行处理 * @param {promise} promise2 promise1.then方法返回的新的promise对象 * @param {[type]} x promise1中onFulfilled的返回值 * @param {[type]} resolve promise2的resolve方法 * @param {[type]} reject promise2的reject方法 */ resolvePromise(promise2,x,resolve,reject) { if (promise2 === x) { 如果从onFulfilled中返回的x 就是promise2 就会导致循环引用报错 return reject(new TypeError('循环引用')); } let called = false; 避免多次调用 如果x是一个promise对象 (该判断和下面 判断是不是thenable对象重复 所以可有可无) if (x instanceof Promise) { 获得它的终值 继续resolve if (x.status === PENDING) { 如果为等待态需等待直至 x 被执行或拒绝 并解析y值 x.then(y => { resolvePromise(promise2,y,reject); },reason => { reject(reason); }); } else { 如果 x 已经处于执行态/拒绝态(值已经被解析为普通值),用相同的值执行传递下去 promise x.then(resolve,reject); } 如果 x 为对象或者函数 } else if (x != null && ((typeof x === 'object') || (typeof x === 'function'))) { try { 是否是thenable对象(具有then方法的对象/函数) let then = x.then; if (typeof then === 'function') { then.call(x,y => { if(called) ; called = true; resolvePromise(promise2,reject); },1)">; reject(reason); }) } 说明是一个普通对象/函数 resolve(x); } } (e) { ; called = ; reject(e); } } else { resolve(x); } } * * [注册fulfilled状态/rejected状态对应的回调函数] * @param {function} onFulfilled fulfilled状态时 执行的函数 * @param {function} onRejected rejected状态时 执行的函数 * @return {function} newPromsie 返回一个新的promise对象 */ Promise.prototype.then = (onFulfilled,onRejected) { const that = this; let newPromise; 处理参数默认值 保证参数后续能够继续执行 onFulfilled = typeof onFulfilled === "function" ? onFulfilled : value => value; onRejected = typeof onRejected === "function" ? onRejected : reason =>throw reason; }; then里面的FULFILLED/REJECTED状态时 为什么要加setTimeout ? 原因: 其一 2.2.4规范 要确保 onFulfilled 和 onRejected 方法异步执行(且应该在 then 方法被调用的那一轮事件循环之后的新执行栈中执行) 所以要在resolve里加上setTimeout 其二 2.2.6规范 对于一个promise,它的then方法可以调用多次.(当在其他程序中多次调用同一个promise的then时 由于之前状态已经为FULFILLED/REJECTED状态,则会走的下面逻辑),所以要确保为FULFILLED/REJECTED状态后 也要异步执行onFulfilled/onRejected 其二 2.2.6规范 也是resolve函数里加setTimeout的原因 总之都是 让then方法异步执行 也就是确保onFulfilled/onRejected异步执行 如下面这种情景 多次调用p1.then p1.then((value) => { // 此时p1.status 由pedding状态 => fulfilled状态 console.log(value); // resolve // console.log(p1.status); // fulfilled p1.then(value => { // 再次p1.then 这时已经为fulfilled状态 走的是fulfilled状态判断里的逻辑 所以我们也要确保判断里面onFuilled异步执行 console.log(value); // 'resolve' }); console.log('当前执行栈中同步代码'); console.log('全局执行栈中同步代码'); // if (that.status === FULFILLED) { 成功态 return newPromise = { setTimeout(() => { { let x = onFulfilled(that.value); resolvePromise(newPromise,reject); 新的promise resolve 上一个onFulfilled的返回值 } (e) { reject(e); 捕获前面onFulfilled中抛出的异常 then(onFulfilled,onRejected); } }); }) } if (that.status === REJECTED) { 失败态 { let x = onRejected(that.reason); resolvePromise(newPromise,reject); } (e) { reject(e); } }); }); } if (that.status === PENDING) { 等待态 当异步调用resolve/rejected时 将onFulfilled/onRejected收集暂存到集合中 { that.onFulfilledCallbacks.push((value) => onFulfilled(value); resolvePromise(newPromise,1)">(e) { reject(e); } }); that.onRejectedCallbacks.push((reason) => onRejected(reason); resolvePromise(newPromise,1)">(e) { reject(e); } }); }); } }; * * Promise.all Promise进行并行处理 * 参数: promise对象组成的数组作为参数 * 返回值: 返回一个Promise实例 * 当这个数组里的所有promise对象全部变为resolve状态的时候,才会resolve。 Promise.all = (promises) { { let done = gen(promises.length,resolve); promises.forEach((promise,index) => { promise.then((value) => { done(index,value) },reject) }) }) } gen(length,resolve) { let count = 0; let values = []; (i,value) { values[i] = value; if (++count === length) { console.log(values); resolve(values); } } } * * Promise.race * 参数: 接收 promise对象组成的数组作为参数 * 返回值: 返回一个Promise实例 * 只要有一个promise对象进入 FulFilled 或者 Rejected 状态的话,就会继续进行后面的处理(取决于哪一个更快) Promise.race = { promises.forEach((promise,1)"> { promise.then(resolve,reject); }); }); } 用于promise方法链时 捕获前面onFulfilled/onRejected抛出的异常 Promise.prototype.catch = (onRejected) { this.then( (value) { { resolve(value); }); } Promise.reject = (reason) { { reject(reason); }); } * * 基于Promise实现Deferred的 * Deferred和Promise的关系 * - Deferred 拥有 Promise * - Deferred 具备对 Promise的状态进行操作的特权方法(resolve reject) * *参考jQuery.Deferred *url: http://api.jquery.com/category/deferred-object/ Promise.deferred = function() { 延迟对象 let defer = {}; defer.promise = { defer.resolve = resolve; defer.reject = reject; }); defer; } * * Promise/A+规范测试 * npm i -g promises-aplus-tests * promises-aplus-tests Promise.js { module.exports = Promise } (e) { }
npm i -g promises-aplus-tests
promises-aplus-tests Promise.js
本站采用系统自动发货方式,付款后即出现下载入口,如有疑问请咨询在线客服!
售后时间:早10点 - 晚11:30点Copyright © 2024 jiecseo.com All rights reserved. 粤ICP备18085929号
欢迎光临【捷杰建站】,本站所有资源仅供学习与参考,禁止用于商业用途或从事违法行为!
技术营运:深圳市晟艺互动传媒有限公司