繁体   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