gpt4 book ai didi

javascript - ComponentDidMount 中的执行顺序

转载 作者:行者123 更新时间:2023-11-28 14:14:01 25 4
gpt4 key购买 nike

我有一个问题:

我在 componentDidMount() 中编写了 4 个函数,但我注意到编写这些函数的顺序不受尊重。

componentDidMount() {
this.checkPermission(); (1)
this.checkInitialBluetoothState(); (2)
this.disconnect() (3)
this.scans() (4)
}

我按顺序收到控制台日志; (3)(2)(1)和(4),有时(4)功能没有执行,应用程序进入循环

您是否建议通过调用将一个函数链接到另一个函数?

谢谢

编辑:

async checkPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION,
{
title: 'Accesso Localizzazione',
message: 'Richiesto accesso localizzazione',
buttonNegative: 'Cancel',
buttonPositive: 'Ok',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("Accesso Localizzazione Permesso.")
}
else {
console.log("Accesso Localizzazione Negato.")
}
} catch (err) {
console.warn(err)
}
}


async checkInitialBluetoothState() {
const isEnabled = await BluetoothStatus.state();
console.log("Controllo bluetooth on o off", isEnabled);
if (isEnabled == true) {
console.log("Bluetooth attivo.")
}
else {
Alert.alert(
'Attenzione:',
'Bluetooth non è attivo.'
);
Actions.homepageutente();
}
}


disconnectDevice() {
if (this.state.device1) {
this.manager.cancelDeviceConnection(this.state.device1.id)
}
else {
console.log("Device1 non connesso")
}
if (this.state.device2) {
this.manager.cancelDeviceConnection(this.state.device2)
}
else {
console.log("Device2 non connesso")
}
}


scans() {
//....

最佳答案

如果您需要异步函数按顺序执行。做这样的事情:

async componentDidMount() {
await this.checkPermission(); (1)
await this.checkInitialBluetoothState(); (2)
this.disconnect() (3)
this.scans() (4)
}

否则,async 函数将立即返回。

关于javascript - ComponentDidMount 中的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58435665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com