node.js - d3 承诺立即开始 - 不等待数据
问题描述
我是新来的。我对结合了 EJS 模板系统和 D3.js 渲染库的 node.js 有疑问。
node.js 文件:
router.post('/foo', function(req, res) {
fs.unlink('./public/d3.json'); // we delete old data (if exist)
res.render('foo'); // page render
//lets suppose that here we request some async data and put them to the array via promises
let array = []; // our array with data
Promise.all(array).then(function(all) { //when we download all the necessary data...
var newArray = JSON.stringify(array);
fs.writeFile('./public/d3.json', newArray, 'utf-8', function(err) { //we write it to file - so chart file bellow can render it
if (err) {
console.log('writing public/d3.json file with newArray failure] - ' + err);
}
else {
console.log('public/d3.json file with content of newArray has been created.');
}
});
});
}
module.exports = router;
我的 EJS 文件如下所示:
<html>
<head></head>
<body>
<div class="chart"></div>
<script>
<% include ../public/d3.js %> // d3 library
<% include ../public/d3_chart.js %> // chart render code
</script>
</body>
</html>
我的图表文件如下所示:
d3.json("../public/d3.json", cb);
function cb(error, data) {
if (error) {
console.log(error);
}
if (data) { // render chart
}
}
但这不起作用。它没有渲染任何东西 - 可能导致 d3.json 文件在 ejs 模板运行 d3_chart.js 时没有数据。但是不应该承诺等待数据然后渲染图表吗?否则在 d3 中使用 Promise 有什么意义?如何让它发挥作用?我觉得我在这里遗漏了一些东西,需要一个建议。谢谢。
解决方案
它与 d3 方面的承诺无关,而是您在服务器上处理请求的方式。
在服务器上,您设置了一些异步过程来构建您想要服务的响应。请求处理程序不会等待异步进程准备好创建响应。
如果您想立即为结果提供服务,请不要在服务器上处理请求时执行异步操作。如果您有来自不同用户的多个请求,则使用本地服务器文件非常糟糕。(这是从其他用户获取数据的一种方式。)您需要在服务器上等待结果。
推荐阅读
- javascript - 为什么在 moment.js 中使用字符串参数指定的时区无法识别?
- c# - 从 Task.Run() 冒泡异常
- wix - 如何使用 wix 安装程序生成一个空文件
- html - 如何将插入符号与面包屑中的文本垂直居中对齐?
- python - 带有列的数据透视表 Pandas 中的百分比计算
- r - 使用循环在R中生成交互式部分依赖图非常慢
- postgresql - 只允许 postgresql 列中的特定值
- javascript - 为什么在这种情况下 console.log 不起作用
- rdf - 如何更改 blazegraph 存储数据的目录?
- javascript - 如何删除数组内对象的重复值?