简体   繁体   English

NodeJS Plotly - 如何在继续之前等待 getImage 完成

[英]NodeJS Plotly - how to wait for getImage to finish before continuing

So, what I am trying to accomplish is basically: Generating a plot by using NodeJS and plotly for NodeJS and getting it into my filesystem (with getImage ), and proceeding with the image afterwards.所以,我想要完成的基本上是:通过使用 NodeJS 和 plotly 生成 plot 并将其放入我的文件系统(使用getImage ),然后继续处理图像。 My problem is, that the function returns before finishing and getting the image into my filesystem.我的问题是,function 在完成并将图像放入我的文件系统之前返回。 So my result is basically that after I'm calling generate_plot() , the file does not exist yet and I'm getting an error.所以我的结果基本上是在我调用generate_plot()之后,该文件还不存在并且我得到了一个错误。 Now onto my question: How do I wait for generate_plot() to finish and to getting the image into my filesystem before continuing and using this image/to use this image?现在我的问题是:如何等待generate_plot()完成并将图像放入我的文件系统,然后再继续使用此图像/使用此图像?

const fs = require("fs");
var plotly = require('plotly')(username, api_key);

function generate_plot(){
    var trace = {
      type: 'bar',
      x: ['Mario', 'Luigi', 'Bowser'],
      y: [50000, 10000, 2000],
      marker: {color: ["red", "green", "darkblue"]},
    };

    var layout = {
      plot_bgcolor: 'rgb(52, 54, 60)',
      paper_bgcolor: 'rgb(52, 54, 60)',
    };

    var chart = {data: [trace], layout: layout};

    var pngOptions = {format: 'png', width: 1000, height: 500};

    plotly.getImage(chart, pngOptions, function (err, imageData) {
        if (err) throw err
        var pngStream = fs.createWriteStream('test.png');
        imageData.pipe(pngStream);
    })
}

function run(){
    generate_plot()
    // proceed with the generated plot which should be in the filesystem
}

Welcome to Stack Overflow!欢迎来到堆栈溢出!

I have removed my previous answers, because (as you correctly pointed out) they didn't solve the full problem.我已经删除了我以前的答案,因为(正如您正确指出的那样)他们没有解决全部问题。

There are two asynchronous tasks that need to complete before we return control outside of the generate_plot() function: retrieving data from Plotly, and writing that content to disk.在我们在generate_plot() function 之外返回控制之前需要完成两个异步任务:从 Plotly 检索数据,并将该内容写入磁盘。

The example below calls generate_plot() , and then (as a test to validate whether the file is really on disk) it immediately copies test.png to test2.png .下面的示例调用generate_plot() ,然后(作为验证文件是否真的在磁盘上的测试)它立即将test.png复制到test2.png Because this results in both files being the same size, this demonstrates that the fs.copyFileSync is not running until the test.png file is fully on disk.因为这会导致两个文件大小相同,这表明fs.copyFileSync直到test.png文件完全在磁盘上才运行。

I did change some of your variable names slightly, but this should work now.我确实稍微更改了一些变量名,但这现在应该可以工作了。

For waiting for the file stream to finish, I reference this question: event associated with fs.createWriteStream in node.js为了等待文件 stream 完成,我参考了这个问题: event associated with fs.createWriteStream in node.js

function generate_plot() {
  return new Promise((resolve, reject) => {
    var trace = {
      type: 'bar',
      x: ['Mario', 'Luigi', 'Bowser'],
      y: [50000, 10000, 2000],
      marker: { color: ["red", "green", "darkblue"] },
    };

    var layout = {
      plot_bgcolor: 'rgb(52, 54, 60)',
      paper_bgcolor: 'rgb(52, 54, 60)',
    };

    var chart = { data: [trace], layout: layout };

    var pngOptions = { format: 'png', width: 1000, height: 500 };

    plotly.getImage(chart, pngOptions, (err, imageStream) => {
      if ( err ) return reject(err);
      var fileStream = fs.createWriteStream('test.png');
      imageStream.pipe(fileStream);
      fileStream.on('error', reject);
      fileStream.on('finish', resolve);
    });
  });
}

function run() {
  generate_plot()
    .then(() => {
      fs.copyFileSync('test.png', 'test2.png');
      console.log('done');
    })
    .catch(err => {
      console.log(err);
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何继续等待一个功能完成? - How to wait for one function to finish before continuing? NodeJS - 如何在继续执行流程之前等待多个异步调用完成? - NodeJS - How to wait for multiple Async calls to finish before continuing execution flow? 如何在继续下一行代码之前等待 .map() 完成执行 - How to wait for .map() to finish executing before continuing on to next lines of code 如何在继续执行脚本之前有效地等待链接文件完成运行 - How to efficiently wait for a linked file to finish running before continuing with script 如何在继续测试之前等待 Vue 组件的异步安装完成 - How to wait for async mounted of Vue component to finish before continuing with testing 如何让程序在继续使用javascript之前等待if语句完成? - How to make the program wait for the if statement to finish before continuing in javascript? 如何在继续async.series之前等待findOneAndUpdate完成 - How to wait for findOneAndUpdate to finish before continuing async.series 如何在继续之前等待递归 function 完全完成? - How can I wait for a recursive function to completely finish before continuing? 节点 - 在继续之前等待地图完成 - Node - wait for map to finish before continuing 等待JS对PHP的调用完成,然后继续 - Wait for a JS call to PHP to finish before continuing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM