The question is in the comments to the code.

export default class Abstract { construct(field = 'defaultField') { this.field = field; } method() { const promise = new Promise((resolve, reject) => { resolve('newField'); }); promise.then( (newField) => { this.field = newField; } ); console.log(this.field); // defaultField - Почему? И как изменить this.field на newField? // Получается я устанавливаю поле this.field для функции then? } } 

Reported as a duplicate at Grundy. javascript 10 Feb '17 at 20:11 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • because the console output is synchronously called. I mean, a bit early. - vp_arth

1 answer 1

Because console.log is a synchronous function, and Promise is asynchronous. So it turns out that console.log shows you this.field before it manages to change its value.

Try to check it yourself:

 // ... method() { const promise = new Promise((resolve, reject) => { resolve('newField'); }) promise.then(newField => { this.field = newField console.log(this.field) ) } 
  • This code in itself does not dispel the author’s doubts that this.field inside then indicates somewhere not there. Simple setTimeout - much more reliable. - vp_arth
  • OK! I just didn’t fully understand the mechanism of work of pasmas. Now everything seems to be clear. Thank! - Andrii Vasilenko