簡體   English   中英

如何在Promise內部調用Promise,在javascript中一次調用2次function

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

我的代碼場景是這樣的:-

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

注意:- 我已經調用 insert() function 2 次

代碼 output:-

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

預計 output:-

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

我想一次多次調用 insert function,有什么辦法可以實現嗎?

非常感謝你提前

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

首先,從then切換到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();

你想要的是等待第一個 function 在第二個開始之前結束,即

await insert()
insert()

這是正確的,但在第一個insert持續時間內暫停整個腳本
為避免這種情況,您可以

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

或者

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

或者

insert().then(insert) // as insert has no args

你應該寫

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

或者,如果你堅持使用then鏈,

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

然后使用insert返回的promise通過await順序執行

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

或通過鏈接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM