Jump to content

How do promises program flow work in javascript?


polaryeti
Go to solution Solved by Strider64,

Recommended Posts

Promises syntax that I learnt:

let p = new Promise(function (resolve, reject) {
  let x = 20, y = 20;
  if (x == y) {
    resolve();

  }
  else {
    reject();
  }
})

p.then(function () {
  console.log("that's correct");
})

  .catch(function () {
    console.log("that's not correct");
  })

  
  
I don't even understand what happens here, the flow control of here. My mild guess is when resolve is called .then part happens, and when reject is called .catch part happens.


I've like read countless articles, banged my head against the wall but it's still not getting inside my head. I feel so dumb for asynchronous javascript.

Please help me understand the program flow step by step in more detail.

Link to comment
Share on other sites

Confusion about how Promises execute is one of the big reasons why async/await exists: that code would otherwise be written as

async function first() {
	let x = 20, y = 20;
	if (x == y) {
		return;
	} else {
		throw undefined;
	}
}

async function second() {
	try {
		await first();
		console.log("that's correct");
	} catch (_) {
		console.log("that's not correct");
	}
}

second();

"async" means the function might not finish running immediately and it implicitly returns a Promise, and "await" means to wait around for whatever function call (Promise) to finish before continuing. But you can more or less ignore those keywords and just look at the code like it was two normal functions.

To answer the question,

1. p is a Promise that starts with a simple function.
2. You add a "layer" to that Promise which says if it executes normally (resolves) then log "that's correct". This creates a second Promise.
3. You add a "layer" to that Promise which says if anything before it executes abnormally/throws (rejects) then log "that's not correct". This includes problems with the p function but also the .then function you passed - because .catch will catch problems with any of the previous Promise "layers", not just the first or the most recent one.
4. At the end of all this you have a Promise which does not get assigned anywhere, but that's okay because you don't care about the (third) Promise itself - you just wanted it to execute, which it does.

If you want to know exactly when each of those steps executes - like literally when it happens - that's a bit of a more complicated subject. The simplest answer would be "as soon as it can", and in the case of your (trivial) example it all happens more or less immediately since none of it needs to try to wait around for anything.

Link to comment
Share on other sites

  • Solution

I did an online tutorial and the following is the basically setup for promises for me as it explains it clearly for me.


    /* Create High Score Data using fetch */
    const createHSTable = (retrieveUrl, succeed, fail) => {

        let max = 5; // Maximum Records to Be Displayed
        let maximum = {};
        maximum.max_limit = max;

        fetch(retrieveUrl, {
            method: 'POST', // or 'PUT'
            body: JSON.stringify(maximum)
        })
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
    };

    createHSTable('retrieveHighScore.php', retrieveHSTableUISuccess, retrieveHSTableUIError);

First it handles any errors

    /* Handle General Errors in Fetch */
    const handleErrors = function (response) {
        if (!response.ok) {
            throw (response.status + ' : ' + response.statusText);
        }
        return response.json();
    };

Second it handles success

    /* retrieve User Data from hs_table */
    const retrieveHSTableUISuccess = function (info) {
        displayHSTable(info);
    };

Lastly it handles failure 😔

    /* If Database Table fails to save data in mysql table */
    const retrieveHSTableUIError = function (error) {
        console.log("Database Table did not load", error);
    };

A nice thing about failure is that you can have it where it doesn't actually fail (example database table not loading):

Here's an example what I'm trying to say:


    /* If Database Table fails to load then answer a few hard coded Q&A */
    const quizUIError = (error) => {
        /*
         * If game database table fails to load then give a few questions
         * and answers, so that the game will still work properly.
         */
        failed = true;
        mainGame.style.display = 'grid';
        d.getElementById('content').scrollIntoView();
        console.log("Database Table did not load", error);
        gameData = [{
            "id": 1,
            "user_id": 1,
            "hidden": "no",
            "question": "[Blank] is the length of time when the film or digital sensor inside the camera is exposed to light, also when a camera's shutter is open when taking a photograph. The amount of light that reaches the film or image sensor is proportional to the [Blank].",
            "category": "photography",
            "answers": [
                "Shutter Speed or Exposure Time",
                "ISO",
                "",
                ""
            ]
        },
            {
                "id": 2,
                "user_id": 1,
                "hidden": "no",
                "question": "[Blank] was one of the earliest photographers in American history, best known for his scenes of the Civil War. He studied under inventor Samuel F. B. Morse, who pioneered the daguerreotype technique in America. [Blank] opened his own studio in New York in 1844, and photographed Andrew Jackson, John Quincy Adams, and Abraham Lincoln, among other public figures.",
                "category": "photography",
                "answers": [
                    "Robert Capa",
                    "Steve McCurry",
                    "Ansel Adams",
                    "Matthew Brady"
                ]
            }
        ]
        totalQuestions = gameData.length;
        //console.log(gameData[gameIndex]);
        createQuiz(gameData[gameIndex]);
    };

 

That's just my way of handling promises and there could be more promises (or less) it's just depends in what you're doing. I find commenting functions makes it easier when you have to look at the code in the future.

Edited by Strider64
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.