How to call Promise inside Promise and call function 2 times at a time in javascript

186 Views Asked by At

My code scenario is like :-

async function ot(a: any) {
    return "outer text " + a;
}

async function it() {
    return "inner text";
}

function insert() {
    it().then(res => {
        console.log(res);
        ot(res).then(resp => {
            console.log(resp);
        });
    });
}

insert();
insert();

NOTE:- I have called insert() function 2 times

Code output:-

"inner text" 
"inner text" 
"outer text inner text"
"outer text inner text"

expected output:-

"inner text"
"outer text inner text"
"inner text"
"outer text inner text"

I want to call insert function more then one time at a single time, is there any way to reach it?

Thank you very much in advance

3

There are 3 best solutions below

2
Konrad On BEST ANSWER

Use then

async function ot(a) {
    return "outer text " + a;
}

async function it() {
    return "inner text";
}

function insert() {
    return it().then(res => {
        console.log(res);
        return ot(res).then(resp => {
            console.log(resp);
        });
    });
}

insert().then(() => insert());

1
Dimava On

First of all, switch from then to await

async function it(): Promise<string> {
    return "inner text";
}
async function ot(a: string): Promise<string> {
    return "outer text " + a;
}
async function insert(): Promise<void> {
    let res = await it();
    console.log(res);
    let resp = await ot(res);
    console.log(resp);
}
insert();
insert();

What you want is to wait for the first function to end before the second starts, being

await insert()
insert()

which is correct but pauses the whole script for the first insert duration
To avoid that you can either

// I probably took that from js minifiers but I always void IIFEs
void async function() {
    await insert()
    insert()
}()

or

insert().then(() => insert())

or

insert().then(insert) // as insert has no args
0
Bergi On

You should write

async function insert() {
    const res = await it();
    console.log(res);
    const resp = ot(res);
    console.log(resp);
}

or, if you insist on using then chains,

function insert() {
    return it().then(res => {
//  ^^^^^^
        console.log(res);
        return ot(res).then(resp => {
//      ^^^^^^
            console.log(resp);
        });
    });
}

and then use the promise that insert returns for sequential execution through await

async function main() {
    await insert();
    await insert();
}
main().catch(console.error);

or through chaining:

insert().then(insert).catch(console.error);