首页 > 解决方案 > 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 有什么意义?如何让它发挥作用?我觉得我在这里遗漏了一些东西,需要一个建议。谢谢。

标签: node.jsd3.jses6-promise

解决方案


它与 d3 方面的承诺无关,而是您在服务器上处理请求的方式。

在服务器上,您设置了一些异步过程来构建您想要服务的响应。请求处理程序不会等待异步进程准备好创建响应。

如果您想立即为结果提供服务,请不要在服务器上处理请求时执行异步操作。如果您有来自不同用户的多个请求,则使用本地服务器文件非常糟糕。(这是从其他用户获取数据的一种方式。)您需要在服务器上等待结果。


推荐阅读