如何在函数中进行同步API调用并返回可链接的?

问题描述 投票:0回答:1

这是我在下面的代码中尝试做的事情。

  1. 在函数内进行三个 API 调用

    areAllTypesFound
    。 使用这些 API 调用的结果来确定我是否获得了所有必要的数据。

  2. 如果我从调用中获取了所有必要的数据,则返回一个包含在可链接中的布尔值。

  3. 在函数

    doStuff
    中,我调用
    areAllTypesFound
    在该调用完成后,我才会对布尔结果执行一些操作。之后,我将执行更多代码。

问题在于,即使找到所有数据,

areAllTypesFound
也始终返回 false。我很确定这与 Cypress 的异步特性有关。有人可以告诉我如何在下面的代码中同步执行所有内容吗?

class MyClass {

    static areAllTypesFound(params) : Cypress.Chainable<boolean> {
        let idsType1 : number[];
        let idsType2 :number[];
        let idsType3 :number[];

        let [type1Present, type2Present, type3Present] = [false, false, false];

        // Here response = Cypress.Response<MyResponseClasses>
        ApiCaller.getItemType1(param1).then((response) => {
            idsType1 = response.body.items.map((item) => item.id);
            type1Present = idsType1.length > 0;
        }
    
        ApiCaller.getItemType2(param2).then((response) => {
            idsType2 = response.body.items.map((item) => item.id);
            type2Present = idsType2.length > 0;
        }

        ApiCaller.getItemType3(param3).then((response) => {
            idsType3 = response.body.items.map((item) => item.id);
            type3Present = idsType3.length > 0;
        }

        const allTypesPresent = type1Present && type2Present && type3Present;
        // optional - maybe print all the "idsType" arrays.

        return cy.wrap(allTypesPresent);
    } 

    static doStuff() : void {
        this.areAllTypesFound(params).then((areFoundBoolean) => {
            if(areFoundBoolean) {
                // do something
            }else {
                // do something else
            }
        });

        // do more stuff only AFTER the above code is completed !
    }

}
typescript cypress
1个回答
0
投票

只需确保在队列上计算总和即可。

// requests happen here, return in random order

let allTypesPresent;

cy.then(() => {
  allTypesPresent = type1Present && type2Present && type3Present;
})

return cy.wrap(allTypesPresent)
© www.soinside.com 2019 - 2024. All rights reserved.