如何检查数据库保存和api调用是否成功



im当前正在编写一个函数,该函数调用另外两个函数。函数1将对象保存到数据库中,函数2执行一个api调用。Api呼叫如下:

async createMSCalendarEntry(start: Date, end: Date, name: string, userID: number, email: string) {
const api_url = `https://graph.microsoft.com/v1.0/users/${vacationEmailforCalendar}/calendar/events`
let graphresponse = await msRestNodeAuth.loginWithServicePrincipalSecret(`${microsoftClientIDforCalendar}`, `${microsoftSecretforCalendar}`, `${microsoftTenantIdforCalendar}`, { tokenAudience: "https://graph.microsoft.com/" })
let token = await graphresponse.getToken()
let newEvent = new Event(start.toISOString(), end.toISOString(), name, userID, email)
var options = {
url: api_url,
json: newEvent.toGraphSchema(),
method: "POST",
headers: {
'content-type': 'application/json',
'Authorization': 'Bearer ' + token.accessToken
}
}
let graphResponse = await this.doRequest(options)
return (graphResponse)
}
async doRequest(options) {
return new Promise(function (resolve, reject) {
request(options, function (error, body) {
if (error) {
reject(error);
}
else {
resolve(body);
}
});
});
}

DB的操作如下:

await this.dataService.TimesRepo.save(vacationDays)

这是调用另外两个的函数的片段:

await this.createMSCalendarEntry(dates.start, dates.end, currentUser.FirstName, currentUser.Id, currentUser.Email)
await this.dataService.TimesRepo.save(vacationDays)
let responseMessage: string = (this.createMSCalendarEntry && this.dataService.TimesRepo.save) ? 'Vacation submitted' : 'Vacation could not be submitted'
res.status(200).send({
message: responseMessage,
data: vacationDays
})
return
}
else {
res.status(400).send("The selected vacation days are in an already planned vacation time!")
return
}

如果这两个函数执行得很好,我想发送响应消息。我现在在那里的尝试不可能是正确的,因为它只是检查函数是否存在。

你能给我一个替代方案吗?问候,Leo

您应该收到这两种方法的响应,然后进行比较以验证两者是否成功,可能是

const calendarResponse = await this.createMSCalendarEntry(dates.start, dates.end, currentUser.FirstName, currentUser.Id, currentUser.Email)
const saveResponse = await this.dataService.TimesRepo.save(vacationDays)
let responseMessage: string = (calendarResponse.<any-property> && saveResponse.<any-property>) ? 'Vacation submitted' : 'Vacation could not be submitted'

您必须识别响应对象的<any-property>,它将具有基于成功/失败的值。您可以简单地使用console.log()响应对象来标识<any-property>应该用来进行比较。