I was going through the link https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Your_second_WebExtension. I could not understand the keyword then() in the choose_beast.js script. I know it is something related to promises in javascript. Can you explain in simple language promises and use of then in this context?
-
https://developers.google.com/web/fundamentals/getting-started/primers/promises https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Daniel Herr Sep 09 '17 at 22:49
-
I already have read it but could not understand in simple terms. – pc.97 Sep 10 '17 at 05:26
-
Related: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) – Makyen Sep 11 '17 at 07:49
1 Answers
Let us compare synchronous and asynchronous code.
Looking at a normal synchronous code:
let a = Date.now();
let b = a * 3;
a
is set before b
is set and it is available for the next line to be used
Looking at an asynchronous code:
let a = someAsyncFuntion();
let b = a * 3; // runs into error
a
is NOT set before b
is set and it is NOT available for the next line to be used, therefore it results in error.
The someAsyncFuntion()
is queued to run when the next process is available. The parser moves to let b = a * 3;
but here the a
is not set yet, so there would be an error.
I simple words, in Promise the function is queued to run asynchronously. Therefore, then()
is when it has done it.
Looking at the example on above page:
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then((tabs) => { browser.tabs.sendMessage(tabs[0].id, {beastURL: chosenBeastURL}); });
browser.tabs.query()
does not run immediately and does not get results immediately. Therefore, we write the code so that when it gets the result then()
do something.
// query tabs asynchronously
var gettingActiveTab = browser.tabs.query({.....});
// once got the result THEN do something
gettingActiveTab.then( /* do something */ );
I hope that helps.

- 7,094
- 7
- 27
- 46