Home > Back-end >  How to call Promise inside Promise and call function 2 times at a time in javascript
How to call Promise inside Promise and call function 2 times at a time in javascript

Time:10-02

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

CodePudding user response:

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());

CodePudding user response:

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

CodePudding user response:

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);
  • Related