如何正确地在Node上重试try语句?

时间:2016-11-27 19:43:42

标签: javascript node.js node-modules steam

继承我的原始代码,基本上它试图接受“交易报价”,如果失败则会被拒绝。如何在相同的“交易报价”中重复此声明10次,间隔几秒,如果之后仍然失败,则拒绝报价?

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class NewFinance2 extends JPanel {
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardHolderPanel = new JPanel(cardLayout);
    private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());

    public NewFinance2() {
        // fill the cardHolderPanel with "cards", JPanels with formula:
        cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
        cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
        cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
        cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
        cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
        cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());

        comboBox.addActionListener(e -> combBoxActionPerformed(e));
        JPanel northPanel = new JPanel();
        northPanel.add(comboBox);

        setLayout(new BorderLayout());
        add(cardHolderPanel, BorderLayout.CENTER);
        add(northPanel, BorderLayout.NORTH);
    }

    private void combBoxActionPerformed(ActionEvent e) {
        FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
        cardLayout.show(cardHolderPanel, selectedFormula.getName());
    }


    // A bunch of dummy methods that don't create much
    // Your real methods would create more complex JPanels
    private JPanel createDecafPanel() {
        return createPanel(FinanceFormula.DECAF);
    }

    private JPanel createCompoundInterestPanel() {
        return createPanel(FinanceFormula.COMPOUND_INTEREST);
    }

    private JPanel createDoublingTimePanel() {
        return createPanel(FinanceFormula.DOUBLING_TIME);
    }

    private JPanel createSimpleInterestPanel() {
        return createPanel(FinanceFormula.SIMPLE_INTEREST);
    }

    private JPanel createPresentValuePanel() {
        return createPanel(FinanceFormula.PRESENT_VALUE);
    }

    private JPanel createNonePanel() {
        return createPanel(FinanceFormula.NONE);
    }   

    // temporary method just for demonstration purposes
    private JPanel createPanel(FinanceFormula financeFormula) {
        JLabel label = new JLabel(financeFormula.getName());
        label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));

        JPanel panel = new JPanel(new GridBagLayout());
        panel.add(label);
        panel.setPreferredSize(new Dimension(400, 300));
        float split = 0.7f;
        float h = (float) (split + Math.random() * (1f - split));
        float s = (float) (split + Math.random() * (1f - split));
        float b = (float) (split + Math.random() * (1f - split));
        Color color = Color.getHSBColor(h, s, b);
        panel.setBackground(color);
        return panel;
    }

    private static void createAndShowGui() {
        NewFinance2 mainPanel = new NewFinance2();

        JFrame frame = new JFrame("Finance");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

2 个答案:

答案 0 :(得分:-1)

回调中有setTimeout()的内容。承诺甚至是ES2017 async-await(babel,TypeScript)可以帮助您获得更清晰的代码。此外,由于错误在回调中传播,因此不需要使用try块,除非您使用的api可能立即失败,但通常不会以回调传递方式失败。

function putOffer(maxRetries) {
    offers.acceptOffer({tradeOfferId: offer.tradeofferid}, function(err, log) {
        if (err) { 
            if (maxRetries > 0) {
                setTimeout(function () { putOffer(maxRetries - 1); }, 2000);
                return;
            }
            helper.log('Error accepting trade offer ' + offer.tradeofferid, 891, err);
            ...
            return;
        }
    });
}

putOffer(10);

答案 1 :(得分:-1)

我想对@AndréWerlang的答案稍加扩展。我的问题是,由于API的限制,我不得不进行数百次调用,并且一旦完成所有Promises后,还利用Promise.all()返回了所有数据。这可能不是理想的,甚至不是Promise.all()的正确用法-但就错误处理而言,它的工作方式符合我的预期:

const requestPromise = (req) => {
    return new Promise((resolve, reject) => {
        const maxRetries = 5;
        function tryRequest(retries) {
                // try a request (http)
                if (someErr) {
                    setTimeOut(()=>{ tryRequest(maxRetries--); }, 2000);
                    return;
                }
                else {
                    // resolve your Promise
                    resolve(data);
                }
        }
    });
}