Asynchronous Promise and then()

191 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.