|
导读网页的本质就是超级文本标记语言,通过结合使用其他的Web技术(如:脚本语言、公共网关接口、组件等),可以创造出功能强大的网页。因而,超级文本标记语言是万维网(Web)编程的基础,也就是说万维网是建立... 网页的本质就是超级文本标记语言,通过结合使用其他的Web技术(如:脚本语言、公共网关接口、组件等),可以创造出功能强大的网页。因而,超级文本标记语言是万维网(Web)编程的基础,也就是说万维网是建立在超文本基础之上的。超级文本标记语言之所以称为超文本标记语言,是因为文本中包含了所谓“超级链接”点。 本篇文章给大家带来的内容是关于Promise实现思路的深入分析(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。Promise实现思路的个人理解 我一直觉得Promise虽然方便,但是它的写法很怪,无法理解实现Promise的人是如何思考的。 不过最近我对于实现Promise的思考过程的有了一点点个人理解,特此记下。 感觉这篇文章我还是没有把思路说清楚,时间紧张,就当做一次记录,回头我要把这个过程在表达的在清楚一点。 用例 var p1 = new Promise2( ( resolve, reject ) => {
setTimeout( () => {
resolve( 'hello' )
}, 1000 )
} )
p1.then( res => {
console.log( res + 'world' )
return res + 'world'
} )
.then( res => {
console.log( res + 'ziwei' )
return res + 'ziwei'
} )我觉得实现一个函数跟封装组件类似,首先从以下几点考虑:
那么结合例子,和这几个问题,我们得到
先实现一个Promise(未实现then的链式调用)
class Promise2 {
constructor( fn ) {
this.successFnArray = [] // 用来缓存successFn和errorFn
this.errorFnArray = []
this.state = 'pendding'
const resolve = ( res ) => { // resolve就做2件事情 1: 修改状态 2:调用successFn
this.state = 'fulfilled'
this.value = res // this.value用来缓存data数据或者error
this.successFnArray.forEach( successFn => {
successFn( res )
} )
}
const reject = ( err ) => {
this.state = 'rejected'
this.value = err
this.errorFnArray.forEach( errorFn => {
errorFn( res )
} )
}
fn( resolve, reject ) // 先调用fn再说
}
then( successFn, errorFn ) {
switch ( this.state ) {
case 'fulfilled':
successFn( this.value ) // 如果调用了resolve,状态就成了fulfilled,就会执行successFn
break
case 'rejected':
errorFn( this.value )
break
case 'pendding':
this.successFnArray.push( successFn ) // 如果还没调用resolve,状态就是pendding,就先把这些异步函数缓存起来。将来resole时调用
this.errorFnArray.push( errorFn )
}
}
}
var p1 = new Promise2( ( resolve, reject ) => {
setTimeout( () => {
resolve( 'hello' )
}, 1000 )
} )
p1.then( res => {
console.log( res + 'world' )
return res + 'world'
} )实现then链式调用 then的实现,和JQ的链式调用不同,JQ是每次调用方法后,把this返回 而Promise规范要求,每次都要返回新的Promise对象 所以只需要把then方法修改一下。 这部分可能会迷惑,但是我想先说一下这里做了哪些事情,其实变化不大 之前的then做了哪些事情?
链式then有哪些改动?
而是调用_successFn,而这个函数内部本质上还是调用successFn(),但同时把调用的返回值作为了resolve的参数,调用了resolve() 因为当successFn被调用,得到返回值时,就表示这个函数执行完了, 就需要执行下一个异步函数了,这样下一个异步函数也会把successFn(res)的return值作为参数 then( successFn, errorFn ) {
return new Promise2( ( resolve, reject ) => {
const _successFn = res => {
resolve(successFn(res))
}
const _errorFn = err => {
reject(errorFn(err))
}
switch ( this.state ) {
case 'fulfilled':
_successFn( this.value )
break
case 'rejected':
_errorFn( this.value )
break
case 'pendding':
this.successFnArray.push( _successFn )
this.errorFnArray.push( _errorFn )
}
} )
}以上就是Promise实现思路的深入分析(代码示例)的详细内容,更多请关注php中文网其它相关文章! 网站建设是一个广义的术语,涵盖了许多不同的技能和学科中所使用的生产和维护的网站。 |
温馨提示:喜欢本站的话,请收藏一下本站!