Search code examples
javascripthttpssequential

Javascript - how to perform sequential execution after https get


I am having a headache learning about javascript sequential execution order and having this code case:

function funcA() {
    var sampleUrl = "https://v2.jokeapi.dev/joke/Programming";

    https.get(sampleUrl, function (response) {
        console.log("http call");
    });
    console.log("funcA");
}

funcA();
console.log("funcB");

I exptected the output order would appeared sequentially like this

http call
funcA
funcB

But the output appeared as follows

funcA
funcB
http call

meaning the output for https.get got delayed even until the printing of funcB.

Is there anyway to make the code output as expected but still hold the structure? I did googling and found some articles talking about async, promise, etc. but really had no idea to intergrate, so very appreciate to learn from your experience.

Thank you in advance!


Solution

  • You can wrap funcA in a promise and resolve the callback.

    function funcA() {
        return new Promise((resolve) => {
            // Start of your code
            var sampleUrl = "https://v2.jokeapi.dev/joke/Programming";
            https.get(sampleUrl, function (response) {
                console.log("http call");
                // Resolve your response
                resolve(response)
            });
            // End of your code
        })
    }
    
    function funcB() { console.log('funcB') }
    async function funcC() {
        return new Promise((resolve) => { console.log('funcC'); resolve() })
    }
    

    Then you can just use it as you would any Asynchronous method.

    (async function init() {
        const jokeResponse = await funcA(); // Await your http.get
        funcB();       // Non-async method
        await funcC(); // Maybe another async method
    })()
    

    Your output would be:

    http call
    funcB
    funcC
    

    As a side note, you can just use the fetch method for simple GET requests. All modern browsers support fetch and it was built to replace http.X methods when the promise wrapper technique shown above became the standard "good way to do it".

    const joke = await fetch("https://v2.jokeapi.dev/joke/Programming").then(res => res.json())