我刚刚开始使用Flutures,我正在尝试获取一些远程数据以使用 d3 进行可视化。
我创建了一个函数,它接受一个 DOM 选择器(例如#my-chart
)和一个 url(例如https://example.com/data.json
)。
如果在获取数据时发生错误,我有一个显示错误消息的一元函数。如果一切顺利,我有一个绘制可视化的一元函数。为了简单起见,我们假设这些函数只是console.error
和console.log
。
const fn = async (selector, url) => {
// convert fetch (which returns a Promise) into a function that
returns a Future
const fetchf = Future.encaseP(fetch);
fetchf(url)
.chain(res => Future.tryP(_ => res.json()))
.fork(console.error, console.log);
}
显然我在包装fetch
未来时遗漏了一些东西,因为我收到了这个警告:
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
如果我不得不使用async/await
我会写这样的东西,这不会给我任何警告。
const fn = async (selector, url) => {
let res;
try {
res = await fetch(url);
} catch (err) {
console.error(err);
return;
}
let data;
try {
data = res.json();
} catch (err) {
console.error(err);
return;
}
console.log(data);
};