Skip to content

Use promise for popup

Posted on:September 15, 2019 at 05:00 AM

Javascript is a single threaded language. We need to offload some part of our code to webAPI’s which you can learn more about in event loop. We are going to take a simple snippet about how we can use Promise.

What is Promise? A Promise is an object eventually return you a value or reject with the reason once the code executes, it will attain three states based on status.

  1. pending - initial state, will achieve this state once you invoke promise code
  2. fulfilled - success state, returns value which intended
  3. rejected - failure state, returns error.
document.getElementById("confirmationBtn").hidden = true;
document.getElementById("response").hidden = true;

function respond() {
    document.getElementById("confirmationBtn").hidden = true;
    document.getElementById("response").innerText="Thanks for confirming..";
    document.getElementById("response").hidden = false;
}

function cancel() {
    document.getElementById("confirmationBtn").hidden = true;
    document.getElementById("response").hidden = true;
}

function invoke() {
    new Promise(respond => {
        document.getElementById("confirmationBtn").hidden = false;
        document.getElementById("response").hidden = true;

        document.addEventListener('response', () => {
            document.removeEventListener('response');
            respond(respond());
        })
    }).then(proceed => {
        if ( proceed ) {
        console.log( proceed );
        } else {
        console.log( proceed );
        }
    })
}
<html>
    <body>
        <button onclick="invoke()">Invoke Promise</button>
        <div id="response"></div>
        <div id="confirmationBtn">
            You are accepting to proceed.
            <button onclick="cancel()">No</button>
            <button onclick="respond()">Yes</button>
        </div>
        <script src="./index.js"></script>
    </body>
</html>

sayanora