javascript - 未决 promise 后 JSON 输入错误意外结束

标签 javascript node.js promise

我正在创建一个数据处理程序,作为该过程的一部分,我需要下载一个文件,然后作为处理程序的一部分进行解析和使用。

我将对文件的请求包装在一个 promise 中,并从其他方法异步调用该方法

我已经包含了来自单独测试文件的处理程序,如下所示

let DataHandler = require('./handler');

const handler = new DataHandler();

console.log(handler.getSupervisors());

getSupervisors方法如下

async getSupervisors() {
    const parsed = await this.loadFile();
    let supervisorList = [];

    parsed.controllers.map(controller => {
        if (controller.rating === 11 || controller.rating === 12){
            supervisorList.push(controller);
        }
    });

    return supervisorList;
}

这称为loadFile方法只需调用 update方法并在返回所需的 json 文件之前。接下来的 2 个方法是 updatedownloadFile我认为这是我的两个问题,如下

async update() {    
    let body = await this.downloadFile();
    const parsedJSON = JSON.parse(body);

    parsedJSON.updated_date = new Date();
    const json = JSON.stringify(parsedJSON);
    fs.writeFile('vatsimData.json', json, function(err, result) {
        if(err) console.log(err);
    });
}

downloadFile() {
    return new Promise((resolve, reject) => {
        const urlList = [
            'http://us.data.vatsim.net/vatsim-data.json',
            'http://eu.data.vatsim.net/vatsim-data.json',
            'http://apac.data.vatsim.net/vatsim-data.json'
        ];
        const url = urlList[Math.floor(Math.random()*urlList.length)];
        request(url, (error, response, body) => {
            if (error) reject(error);

            if (response.statusCode !== 200) {
                reject('Invalid status code <' + response.statusCode + '>');
            }

            resolve(body);
        });
    });
}

getSupervisors 的输出方法应该是 json 文件中所有“主管”的数组,而不是返回 Promise { <pending> }和这个错误

(node:3160) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at DataHandler.loadFile (D:\Projects\VATSIM-Data-Handler\handler.js:57:15)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:3160) 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(). (rejection id: 1)
(node:3160) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

我尝试将整个 update .then 中的方法调用downloadFile后回调但没有成功

我的loadFile方法如下

async loadFile(){
    await this.update();
    return(JSON.parse(fs.readFileSync('vatsimData.json', {encoding:'utf-8'})));
}

最佳答案

您得到 promise 的原因是,当您 console.log(handler.getSupervisors()) 时,您没有等待 async 函数;

你应该这样做

handler.getSupervisors.then(val => console.log(val));

该错误可能是因为服务器的 body 响应格式可能不正确。在调用 JSON.parse() 之前尝试 console.log 正文,并使用 try catch 包装并防止未处理的错误

更新 从评论中,您正在尝试解析使用不正确的编码读取的文件

console.log(JSON.parse(fs.readFileSync('vatsimData.json',{encoding:'utf-8'})));

在选项中添加编码值。

更新

async update() {    
    let body = await this.downloadFile();
    const parsedJSON = JSON.parse(body);

    parsedJSON.updated_date = new Date();
    const json = JSON.stringify(parsedJSON);
    fs.writeFileSync('vatsimData.json', json, function(err, result) {
        if(err) console.log(err);
    }); // convert it to sync or resolve with a new promise when you complete the write to wait for the loadFile to have the file ready
}

关于javascript - 未决 promise 后 JSON 输入错误意外结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58331172/

相关文章:

javascript - NodeJS Promise.all 正在等待所有组件完成后再继续

php - 如何根据php变量在一定时间后自动重新加载页面

javascript - jQuery 和处理元素 ID

node.js - Node.js + Express 中的表单上传(通过多方)

javascript - 如何知道调用脚本的目录?

node.js - 什么是url解码和url编码

javascript - 如何在 node.js 中创建一个 Get 请求以按日期(可以是月、日或年)对请求求和?

javascript - 将 ionicTimePicker 舍入到最接近的 30 分钟间隔

javascript - 如何在 Javascript 中正确链接 Promise,并考虑错误处理?

javascript - 等待 promise - 代码挂起