简体   繁体   中英

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

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM