You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义MyPromise类中resolve无法调用then方法的问题求助

问题分析与解决

核心原因:this指向丢失

当你把this.resolve作为参数传给构造函数的回调cb时,resolve函数的上下文(this)已经和MyPromise实例解绑。外部调用resolve(42)时,resolve内部的this不再指向MyPromise实例,导致this.then无法找到对应的方法。

修复方案

有两种常用的修复方式:

方式1:在构造函数中绑定this

通过bind方法将resolve和reject的this固定为MyPromise实例:

class MyPromise{
    
    constructor(cb){
        // 绑定this到resolve、reject,确保调用时上下文指向实例
        this.resolve = this.resolve.bind(this);
        this.reject = this.reject.bind(this);
        cb(this.resolve, this.reject)
    }
  
    resolve(value){
        this.then(value)
    }
  
    then(val){
        console.log("here")
        return val;
    }
  
    reject(){
    }
  
}

var p = new MyPromise((resolve, reject)=>{
    resolve(42)
});

方式2:用箭头函数定义方法

箭头函数会自动继承构造函数的this上下文,无需手动绑定:

class MyPromise{
    
    constructor(cb){
        cb(this.resolve, this.reject)
    }
  
    // 箭头函数自动绑定构造函数的this
    resolve = (value) => {
        this.then(value)
    }
  
    then(val){
        console.log("here")
        return val;
    }
  
    reject = () => {
    }
  
}

var p = new MyPromise((resolve, reject)=>{
    resolve(42)
});

补充说明

你之前尝试的this.self = this无效,是因为resolve内部的this已经不是实例,this.self根本不存在。如果要沿用这种思路,需要在构造函数中将self注入到resolve的作用域,但显然上述两种绑定this的方式更简洁规范。

内容的提问来源于stack exchange,提问作者ABGR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:44:50