代码之家  ›  专栏  ›  技术社区  ›  Sasha Grievus

如何在typescript中修改promise内的变量(范围和“this”问题)?

  •  0
  • Sasha Grievus  · 技术社区  · 7 年前

    我已经使用typescript 2.2.1在ionic 4.5.0中建立了一个项目。

    在它里面,我有两个班

    file functions.ts
    /* lots of import */
    @Injectable()
    export class Functions {
      language: string;
    }
    
    file fooclass.ts
    /* lots of import and import of functions.ts */
    export class FooClass {
       constructor(public functions: Functions) {
         this.functions.language="ENG";
       }
    
       somefunction() {
         console.log("1 - language: "+this.functions.language);
         this.someotherfunction().then((response) => {
            console.log("2 - language: "+this.functions.language);
         })
         console.log("3 - language: "+this.functions.language);
       }
    
    someotherfunction() {
      return new Promise((resolve) => {
         this.functions.language="ITA";
         resolve("done");   
      }
    }
    

    这是打印出来的

    1 - language: ENG
    2 - language: ITA
    3 - language: ENG
    

    我认为使用胖箭头可以绑定'this'环境,以便对this.functions的变量'language'进行更改可以在其他函数的允诺中存活下来,但似乎不行。如何修改变量语言并使更改在承诺之外继续存在?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Drew Reese    7 年前

    functions

    class FooClass {
      constructor() {
        this.language="ENG";
      }
    
      somefunction() {
        console.log("1 - language:" + this.language);
        this.someotherfunction()
        .then((response)=>{
          console.log("2 - language: " + this.language);
        });
        console.log("3 - language: " + this.language);
      }
    
      someotherfunction() {
        return new Promise((resolve) =>{
          this.language = "ITA";
          resolve("done");   
        });
      }
    }
    
    const foo = new FooClass();
    foo.somefunction();

    保存“函数”参数时,它也起作用:

    class FooClass {
      constructor(functions) {
        this.functions = functions;
      }
    
      somefunction() {
        console.log("1 - language:" + this.functions.language);
        this.someotherfunction()
        .then((response)=>{
          console.log("2 - language: " + this.functions.language);
        });
        console.log("3 - language: " + this.functions.language);
      }
    
      someotherfunction() {
        return new Promise((resolve) =>{
          this.functions.language = "ITA";
          resolve("done");   
        });
      }
    }
    
    const foo = new FooClass({ language: "ENG"});
    foo.somefunction();
    推荐文章