如何在打字稿中修改Promise中的变量(范围和“此”问题)?

时间:2019-01-02 16:50:20

标签: javascript typescript promise

我已经使用打字稿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的变量“ language”进行更改,功能可以在promise otherotherfunction中生存,但事实并非如此。我该如何修改可变语言,并使更改在承诺范围之外得以生存?

编辑:我现在意识到问题是从ionic的早期版本升级后产生的。也许它不应该表现得像这样,那是一些臭虫? (我具有该软件的先前版本,并且正在使用相同的代码运行)

1 个答案:

答案 0 :(得分:0)

在构造函数中如何使用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();

保存functions参数时,它也可以工作:

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();