Search code examples
javascriptfunctionasynchronoussynchronous

JavaScript Asynchronous Function Process


fetchAssets( ) is an async JavaScript function. Could someone please explain to me how the code below works?

var x = 5;
this.fetchAssets()
.then(() => {navigate('Auth');})
.catch(error => console.error(`Error while loading: ${error.stack}`));
var y = 6;

Does it work like this?:

1: var x = 5 is executed. When that finishes, #2 starts

2: fetchAssets( ) is called

3: var y = 6 is executed

4: Whenever fetchAssets returns, we navigate to 'Auth'.

OR do we wait for fetchAssets( ) to complete before executing var y = 6?


Solution

  • Not quite. Here is a more accurate version:

    1. var x = 5 is executed
    2. fetchAssets() is called
    3. .then() is called on the return value of fetchAssets
    4. .catch() is called on the return value of .then
    5. var y = 6 is executed
    6. Whenever the promise returned by fetchAssets is resolved, navigate() is called

    Especially this part is either wrong or just not expressed very well:

    Whenever fetchAssets returns, we navigate to 'Auth'.

    fetchAssets returns immediately before the assignment to y happens. Functions always return synchronously.