【问题标题】:Adding an early return to avoid using else and additional nesting添加提前返回以避免使用 else 和额外的嵌套
【发布时间】:2021-11-10 06:34:12
【问题描述】:

我从开发人员那里得到以下评论: “在此处添加提前返回以避免使用 else 和额外的嵌套”。但是我修改有点困难。

你能告诉我在这种情况下我应该怎么做吗? 谢谢!

failOnStatusCode: false,

    }).then((res) => {


      // Assertion for one by one

      if (res.status != 200) {

        cy.log(JSON.stringify(res));

      } else {

        expect(res.body.id).to.eq(vehicleIdBuyNow);

        expect(res.body.auctionStatus).contains("finished");

        expect(res.body.price).to.be.equal(minPrice);

        expect(res.body.winningBidPlatformId).contains(platformIdBuyNow);

        expect(true).to.be.true;

【问题讨论】:

    标签: javascript node.js if-statement cypress


    【解决方案1】:

    建议改成:

    .then((res) => {
        if (res.status != 200) {
            cy.log(JSON.stringify(res));
            return; // exit function, no need for an `else` after this
        }
        expect(res.body.id).to.eq(vehicleIdBuyNow);
        expect(res.body.auctionStatus).contains("finished");
        expect(res.body.price).to.be.equal(minPrice);
        expect(res.body.winningBidPlatformId).contains(platformIdBuyNow);
        expect(true).to.be.true;
    

    【讨论】:

    • if (res.status != 200) return cy.log(JSON.stringify(res));
    • 我希望代替 JSON.stringify,如果可能的话,自己进行转换,它在 CPU 上的成本更低(如果这是服务器端的)。
    • 我只会在下一个.then 使用该返回值的情况下这样做,这不太可能 - 否则,如果没有返回任何内容,代码的意图会更清晰。
    • 完美,一切都涵盖了! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2023-03-29
    相关资源
    最近更新 更多