[英]writing a function with callback in reactjs
reference-url: https://fullcalendar.io/docs/events-function参考网址: https://fullcalendar.io/docs/events-function
The below is a way to provide events as a function to to the FullCalendar. How would I write this in a react functional component, I fetch the data using graphql, which is a bit different.下面是一种将事件作为 function 提供给 FullCalendar 的方法。我将如何在反应功能组件中编写它,我使用 graphql 获取数据,这有点不同。
function(info, successCallback, failureCallback) {
req.get('myxmlfeed.php')
.type('xml')
.query({
start: info.start.valueOf(),
end: info.end.valueOf()
})
.end(function(err, res) {
if (err) {
failureCallback(err);
} else {
successCallback(
Array.prototype.slice.call( // convert to array
res.getElementsByTagName('event')
).map(function(eventEl) {
return {
title: eventEl.getAttribute('title'),
start: eventEl.getAttribute('start')
}
})
)
}
})
and here's my current function, it returns a simple array.. how would I implement the callback and callback fail as they mentioned in the documents.这是我当前的 function,它返回一个简单的数组。我将如何实现文档中提到的回调和回调失败。
const fetchData = async () => {
const { searchEvents: myEvents } = await searchEvents()
try {
const data = myEvents.content.forEach((x) => {
x.start = new Date(x.start)
x.end = new Date(x.end)
})
setIsPageLoaded(true)
calendarRef.current.getApi().addEventSource(data)
return clonedata
} catch (err) {
console.log(err)
}
return true
}
I would recommend writing a simple fetchFeed
function that only takes care of fetching the data.我建议编写一个简单的fetchFeed
function,它只负责获取数据。 Using promises, you can avoid the many drawbacks of callback-oriented designs -使用承诺,您可以避免面向回调设计的许多缺点 -
function fetchFeed (start, end) {
return new Promise((success, failure) => {
req
.get("myxmlfeed.php")
.type("xml")
.query({ start, end })
.end((err, res) => {
if (err)
failure(err)
else
success(res)
})
})
}
Now we can call fetchFeed
with some startDate
and some endDate
.现在我们可以用一些startDate
和一些endDate
调用fetchFeed
。 The positive result can be processed in .then(...)
and any error can be addressed in .catch(...)
-可以在 .then(...) 中处理正结果.then(...)
并且可以在.catch(...)
中解决任何错误 -
fetchFeed(startDate, endDate)
.then(res => {
// ...
})
.catch(err => {
console.log(err)
})
Promises received additional support with async
and await
syntax that makes writing this kind of program even more natural - Promises 获得了async
和await
语法的额外支持,这使得编写此类程序更加自然 -
async function updateFeed (...) {
const res = await fetchFeed(startDate, endDate)
for (const e of res.getElementsByTagName("event")) {
// ...
}
}
updateFeed(...).then(console.log).catch(console.error)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.