【问题标题】:Call async function in a while loop [duplicate]在while循环中调用异步函数[重复]
【发布时间】:2022-01-26 00:01:44
【问题描述】:

我必须从 BLE 设备中读取一个值,然后写入另一个值,所以这是我的功能:

   getBit = (device) => {
        try {
            device.readCharacteristicForService(this.state.sUuid, this.state.cUuid2)
            .then((read) => {
                switch (this.toHexByte(read.value)) {
                    case 'ee':
                        this.setState({ countC0: 0 });
                        break;
                    case 'c0':
                        this.setState({ countC0: this.state.countC0 + 1 });
                        break;
                    default: // the bit I want to stock
                        this.setState({
                            resId: [...this.state.resId, this.toHexByte(read.value)],
                            countC0: 0
                        });
                        break;
                }
                device.writeCharacteristicWithoutResponseForService(this.state.sUuid, this.state.cUuid2, this.state.respBit)
            })
            return
        }
        catch (err) {
            console.log("find catch error:", err);
        }
    }

但我必须调用这个函数,直到我得到相同的位 ('c0') 3 次,所以我这样循环:

   while (countC0 < 15) {
     this.getBit(device);
     countC0++;
   }

问题是我收到 Please report: Excessive number of pending callbacks: 501 错误,因为我在 while 循环中调用异步函数。

【问题讨论】:

    标签: javascript react-native loops async-await promise


    【解决方案1】:

    应该这样做

    getBit = async (device) => {
        try {
            const read = await device.readCharacteristicForService(this.state.sUuid, this.state.cUuid2)
    
    
            switch (this.toHexByte(read.value)) {
                case 'ee':
                    this.setState({ countC0: 0 });
                    break;
                case 'c0':
                    this.setState({ countC0: this.state.countC0 + 1 });
                    break;
                default: // the bit I want to stock
                    this.setState({
                        resId: [...this.state.resId, this.toHexByte(read.value)],
                        countC0: 0
                    });
            }
    
            device.writeCharacteristicWithoutResponseForService(this.state.sUuid, this.state.cUuid2, this.state.respBit)
        }
        catch (err) {
            console.log("find catch error:", err);
        }
    }
    
      while (countC0 < 15) {
         await this.getBit(device);
         countC0++;
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-05
      • 2018-09-25
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多