我刚开始使用
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);
};