我有四个函数,每个函数内部都有一个循环。根据第一个功能循环的完成情况,应调用第二个功能,而第二个功能循环的完成情况应调用第三个功能。
我使用了async并等待,但是没有用。
谁能告诉我我的代码出了什么问题?
第一个功能:
selectedUser = (userName, userId) => {
this.isFilterByNameSelected = true;
this.props.dispatch(fetchDuesChitties()).then((datas) => {
Object.keys(datas).map((key) => {
if (datas[key].chittieUsers) {
let chittieUsers = datas[key].chittieUsers;
Object.keys(chittieUsers).map((userKey) => {
if (chittieUsers[userKey].userId === userId) {
this.userTicketNumber[key] = {
name: userName,
chitId: datas[key].chitId,
chittieId: key,
chitName: datas[key].chitName,
chittieName: datas[key].chittyName,
auctionsCompleted: datas[key].auctionsCompleted,
userId: userKey
};
}
});
}
});
this.getChittiePayment();
});
};
第二功能:
getChittiePayment = () => {
Object.keys(this.userTicketNumber).map((key) => {
let totalAmount = 0;
let auctionsCompleted = this.userTicketNumber[key].auctionsCompleted;
let chitId = this.userTicketNumber[key].chitId;
let paymentDetails = this.props.chits[chitId].paymentDetails;
for (var i = 0; i < auctionsCompleted; i++) {
totalAmount += parseInt(paymentDetails[i].dueAmount);
}
this.userTicketNumber[key].totalAmount = totalAmount;
});
this.getUsersDuePayment();
}
第三功能:
getUsersDuePayment = () => {
Object.keys(this.userTicketNumber).map((key) => {
let customerId = this.userTicketNumber[key].userId;
let auctionsCompleted = this.userTicketNumber[key].auctionsCompleted;
this.props.dispatch(fetchPaymentsByUserId(customerId, auctionsCompleted)).then((payments) => {
this.userTicketNumber[key].amountPaid = payments;
});
});
this.getBalanceAmount();
}
第四功能:
getBalanceAmount = () => {
Object.keys(this.userTicketNumber).map((key) => {
let userKey = this.userTicketNumber[key];
if (userKey.totalAmount && userKey.amountPaid) {
let balanceAmount = userKey.totalAmount - userKey.amountPaid;
this.userTicketNumber[key].pendingAmount = balanceAmount;
}
});
this.setState({ userFilter: this.userTicketNumber });
}
答案 0 :(得分:1)
您必须从第二个和第三个函数返回一个Promise才能完成这项工作。请尝试以下示例。希望对您有帮助。
async function First(){
console.log('Firts Func started');
await Second();
console.log('End');
}
function Second(){
return new Promise(async (resolve,reject)=>{
console.log('At Second Function');
await Third();
console.log('Second func end');
resolve('Data From Second function');
});
}
function Third(){
return new Promise(async (resolve,reject)=>{
console.log('At Third Function');
await Fourth();
console.log('Thidr func end');
resolve('Data From Third function');
});
}
function Fourth(){
return new Promise((resolve,reject)=>{
console.log('At Fourth Function');
console.log('Fourth func end');
resolve('Data From Fourth function');
});
}
First();