【问题标题】:How do i wait for a function (toString()) to be finish before using that variable?在使用该变量之前,我如何等待函数 (toString()) 完成?
【发布时间】:2020-02-07 23:58:24
【问题描述】:

我尝试将缓冲区转换为字符串并尝试将其解析为 Json。但有时它会在字符串操作完成之前尝试转换为 Json。

在下面的代码中,我试图将变量 dat 中的缓冲区数据转换为字符串并将其解析为 JSON。所以有时候 JSON.parse 会抛出一个错误(Incomplete json format to parse)。

var apicall = {
    url: API,
    method: 'post',
    responseType: 'stream',
    headers: {
        'Content-Type': 'application/json',
    },
    data: body
}
axios(apicall).then((res) =>{
   var writer = new MemoryStream(null, {
       readable : true
   })
   res.data.pipe(writer)
   writer.on('data',function(dat){  
       console.log(dat);
       var e = dat.toString();
       var jsondata = JSON.parse(e);
       console.log(jsondata);
   });
}).catch((e)=>{
    console.log(e);
})

请求某人帮助我如何等待 toString 函数完成其过程

【问题讨论】:

  • 在被告知如何处理流之前访问writer 流不是问题吗?将pipe 移动到writer.on 声明之后会改变什么吗?没用过axios,很好奇。

标签: javascript node.js json stream


【解决方案1】:

这种方法的问题在于,您将收到分块的响应,默认值为 16KB,因此如果您的 json 大于该值,它将以多个块的形式出现。

修复算法的一种方法是将所有这些块存储到一个单独的数组中,并在流完成 end 事件后对其进行解析:

let body = [];
writer.on('data', (chunk) => {
  body.push(chunk);
}).on('end', () => {
  body = Buffer.concat(body).toString();
  // at this point, `body` has all the chunks stored in as a string
  // here you will be able to JSON.parse the body
  const json = JSON.parse(body);
});

该方法的缺点是它不适用于超过 1.7GB 的超大文件,因为它们不适合内存。

【讨论】:

    猜你喜欢
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    相关资源
    最近更新 更多