ed2
ed2

Reputation: 1497

How to run 2 lines of Javascript in sequence - async/promises/callbacks

I need to run two (or more) lines of code in sequence in vanilla javascript.

Each invokes calls to routines (aka top level functions, which have a purpose of performing procedural steps rather than calculating a result). These in turn call multiple others.

function fMasterProcedure() {
    fSubProcedure1();
    fSubProcedure2();
    ... etc
}

Suppose the code for fSubProcedure1() is as follows (for this illustration):

function fSubProcedure1() {
    fSubSubProcedure1_1();  // Normal
    fSubSubProcedure1_2();  // Async
    fSubSubProcedure1_3();  // Normal
    fSubSubProcedure1_4();  // Async
    fSubSubProcedure1_5();  // Normal
}

This is literally the same question as here how to run sequence functions in javascript, although the answers provided there do not show how to do it, and there have been syntax updates in the years since in relation to promises and asynchronous functions.

These days the answer seems to be promises and async/await... or is it just callbacks without using promises?

I have read many descriptions and tutorials on promises, including here.

However, I end up with code like this:

function fMasterProcedure() {
    return (new Promise(function(resolve, reject) {
        fSubProcedure1();
        setTimeout(function () {
            resolve();
        }, 0);
    })).then(function(result) {
        fSubProcedure2();
    });
}

As you can see, it adds 400% more lines unnecessarily and still doesn't work reliably.

Is there a more efficient way to write this, or a more appropriate way?

(The requirement is to run fSubProcedure2 after fSubProcedure1 (and any of its child processes) are completed in full. I am trying to move from "that's not how JS works" to "here's how to make JS achieve that requirement").

I'm trying to get the good understanding so I can apply it to a whole project approach - there are many examples within, of each.

Upvotes: 1

Views: 1630

Answers (1)

Gray Hat
Gray Hat

Reputation: 368

If fSubProcedure1 and fSubProcedure2 are two asynchronous functions and you wanna execute them one after the other then try to go for something like :

async function fMasterProcedure() {
    await fSubProcedure1();
    await fSubProcedure2()
}
// to execute the fMasterProcedure function
fMasterProcedure().then(console.log).catch(console.error);
//replace console.log and console.error with your appropriate callbacks

Example :

// returns Promise<number>
function fSubProcedure1() {
    console.log("runs first");
    return Promise.resolve(2*2);
}
// returns void
function fSubProcedureNormal() {
    console.log("runs second");
    //returns nothing
}
// returns number which gets converted to Promise<number>
async function fSubProcedure2() { 
    console.log("runs third");
    return 2*4;
}
async function fMasterProcedure() {
    let a = await fSubProcedure1();
    fSubProcedureNormal();
    let b = await fSubProcedure2();
    return `${a} : ${b}`;
}

fMasterProcedure().then(console.log).catch(console.error);

One important point... You would wanna try and catch error inside fMasterProcedure for every await

Resources :

async function

async await

Check out these resources to learn more

Upvotes: 1

Related Questions