我的函数生成一个随机数,并检查它是否已经存在于数据库中。问题是我在注册新用户时使用了此函数,并且需要在此处添加一个Promise,以便该函数不会返回null。
有人可以告诉我我该怎么写,以便可以确定首先返回import * as React from 'react';
import { Text, View, StyleSheet,Button } from 'react-native';
import RadioForm, { RadioButton, RadioButtonInput, RadioButtonLabel } from 'react-native-simple-radio-button';
export default class App extends React.Component {
state = {
ages: [
{key:1,label:20},
{key:2,label:30},
{key:3,label:40},
],
initialRadioPos: -1
}
render() {
return (
<View style={styles.container}>
<View
style={{
flexDirection: 'column',
marginTop: 10,
alignItems: 'flex-start',
}}>
<RadioForm
radio_props={this.state.ages}
initial={this.state.initialRadioPos}
formHorizontal={false}
labelHorizontal={true}
buttonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
selectedButtonColor={this.state.switched ? '#673AB7' : '#A9A9A9'}
onPress={currentAge => {
this.setState({ currentAge });
}}
/>
<Button title="submit" onPress={()=>this.clear()}/>
</View>
</View>
);
}
clear = () =>{
this.setState({
initialRadioPos:-1
})
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
。
getAccountBill()
我的注册控制器:
function getAccountBill() {
const accountBill = `2222${Math.floor(
Math.random() * 90000000000000000000,
) + 10000000000000000000}`;
Bill.findOne({
where: {
account_bill: accountBill,
},
})
.then(isAccountBill => {
if (isAccountBill) {
getAccountBill();
}
console.log('accountBill', accountBill);
return accountBill;
})
.catch(err => {
/* just ignore */
});
}
答案 0 :(得分:3)
鉴于getAccountBill
内部对Mongo进行了异步调用,您可以返回其结果并await
对其进行调用,然后再调用Bill.create
。
async
/ await
使以同步方式编写异步代码变得非常容易。
async function getAccountBill() {
const accountBill = `2222${Math.floor(
Math.random() * 90000000000000000000,
) + 10000000000000000000}`;
try {
const acct = await Bill.findOne({
where: {
account_bill: accountBill,
},
});
return acct ? await getAccountBill() : accountBill;
} catch(e) {
// if you ignore the error, at least log it
console.error(e);
}
}
然后在控制器中,等待帐号,然后再创建帐户
const user = await User.create({
login: req.body.login,
password: req.body.password,
name: req.body.name,
surname: req.body.surname,
email: req.body.email,
date_registration: getTodayDate(),
});
const account_bill = await getAccountBill();
const bill = await Bill.create({
id_owner: user.id,
account_bill,
available_funds: getAvailableFunds(),
})
const additional = await Additional.create({
id_owner: user.id,
account_balance_history: getAccountBalanceHistory(),
});
res.status(200).json({ register: true });