串行执行异步函数

时间:2021-07-19 23:35:35

标签: javascript node.js function asynchronous

我正在尝试将此代码放入两个异步函数中。我已经设法将身份验证检查放入一个检查中,
但是我很难将 api 调用放入异步函数中,因为它必须编写 json 文件。
我怎样才能告诉身份验证函数运行在我写完 json 文件之后?

var authVal = 2;
var condition1 = 3;
var condition2 = 5;
var condition3 = 8;
const fs = require('fs');
const https = require('https');
const util = require('util');
const read = util.promisify(fs.readFile);
let cmdrName = args.join(' ');
let currTime = new Date().toISOString().slice(0, 19);
cmdrName = cmdrName.toLowerCase();

console.log("\x1b[33m" + message.author.username + "\x1b[37m" + " has used " + "\x1b[33m" + ".auth " + cmdrName);

//api call
const data = new TextEncoder().encode(
    JSON.stringify({ "header": { "appName": "CIABot", "appVersion": "1.0", "isDeveloped": true, "APIkey": "" }, "events": [{ "eventName": "getCommanderProfile", "eventTimestamp": currTime, "eventData": { "searchName": cmdrName } }] })
)

const options = {
    hostname: 'inara.cz',
    port: 443,
    path: '/inapi/v1/',
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Content-Length': data.length
    }
}

const req = https.request(options, res => {
    console.log(`statusCode: ${res.statusCode}`);

    res.on('data', d => {
        fs.writeFile('./comms/inaraOutput.json', d, function (err) {
            if (err) throw err;
            console.log("\x1b[32m" + "successfully created " + "\x1b[33m" + "inaraOutput.json");
            console.log("\x1b[37m" + "------");
        });
    });
})

req.on('error', error => {
    console.error(error);
})

req.write(data);
req.end();
//api call ends here

//auth check
var auth = async () => {
    const [json1, json2] =
        await Promise
            .all([
                read("./comms/code.json"),
                read("./comms/inaraOutput.json")
            ])
    let jsonCode = JSON.parse(json1);
    let inaraOutput = JSON.parse(json2);

    //fancy auth logic here
};

auth();

1 个答案:

答案 0 :(得分:0)

您可以将所有异步调用包装在另一个异步函数中,并在执行 OAuth 之前等待执行完成。

async function myFunction(){
    await req.on('error', error => {
        console.error(error);
    })
    
    await req.write(data);
    await req.end();
    auth();   
}
myFunction()