这是我在下面的代码中尝试做的事情。
在函数内进行三个 API 调用
areAllTypesFound
。
使用这些 API 调用的结果来确定我是否获得了所有必要的数据。
如果我从调用中获取了所有必要的数据,则返回一个包含在可链接中的布尔值。
在函数
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 !
}
}
只需确保在队列上计算总和即可。
// requests happen here, return in random order
let allTypesPresent;
cy.then(() => {
allTypesPresent = type1Present && type2Present && type3Present;
})
return cy.wrap(allTypesPresent)