我有函数调用另一个函数来返回字符串,但我未定义。因为首先执行读取文件[重复]

问题描述 投票:0回答:2

我不是那么专家,但我可以处理: 这调用了函数 checkTLS

// params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

Object.keys(params).forEach( key => {
    console.log(key);
    if(key.includes("tls")){ 
        //splitting parms to get cluster id
        clusterId=key.substring(0, key.indexOf("_"));
        console.log("cluster ID=="+clusterId);
        tlsresualt= checkTLS(clusterId);
        console.log("tls resualt is="+ tlsresualt);
        req.body[`${clusterId}_tls`]=tlsresualt;
        console.log(req.body.ibmdev_tls);
        console.log("==================================");
    }
});

checktlsStatus是我需要通过的:

function checkTLS(clusterID){
    fs.readFile("clusterinfo/clusterinfo.json",(err, clusters) => {
        TlsVerion="TLS12";
        if(TlsVerion.includes("TLS12")){ 
            console.log(`TLs check status ------------------------ for ${clusterID}`);
            console.log(` TLs match the Secuity Baseline requirment for ${clusterID}`);
            checktlsStatus="implemented";
            //req.body.ibmdevtls=tlsStatus;
            //return console.log(checktlsStatur+ "check for tls successed");
            // req.body.(`${clusterID}`+`tls`)=tlsStatus;
            return checktlsStatus;
        }
    )};
}

我尝试过await和asycn,也尝试过execSync(

sleep 20
);

javascript node.js function debugging javascript-objects
2个回答
0
投票

回调不能那样工作!

想一想:

function foo(name, callback) {
  callback(name.length);
}

function bar() {
  const abc = foo("something", (n) => {
    return n + 10;
  });
  console.log(abc);
}

bar();

abc
将始终未定义,因为 foo 没有返回值!

回调返回值被

foo
省略。

这就是您所认为的

fs.readFile
的工作原理。但它不是那样工作的!


有办法解决它:

  1. checkTLS
    函数添加回调。
  2. 使用
    fs.readFileSync
  3. (推荐)使用
    Promise
    (异步/等待)API。

我们开始吧:

const fs = require("fs");
params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

Object.keys(params).forEach(async (key) => {
    console.log(key);
    if(key.includes("tls")){ 
        //splitting parms to get cluster id
        clusterId=key.substring(0, key.indexOf("_"));
        console.log("cluster ID=="+clusterId);
        // this changed
        const tlsresualt = await checkTLS(clusterId);
        console.log("tls resualt is="+ tlsresualt);
        // req.body[`${clusterId}_tls`]=tlsresualt;
        // console.log(req.body.ibmdev_tls);
        console.log("==================================");
    }
});

async function checkTLS(clusterID){
    const clusters = await fs.promises.readFile("clusterinfo/clusterinfo.json");
    TlsVerion="TLS12";
    if(TlsVerion.includes("TLS12")){ 
        console.log(`TLs check status ------------------------ for ${clusterID}`);
        console.log(` TLS match the Security Baseline requirement for ${clusterID}`);
        checktlsStatus="implemented";
        //req.body.ibmdevtls=tlsStatus;
        //return console.log(checktlsStatur+ "check for tls succeeded");
        // req.body.(`${clusterID}`+`tls`)=tlsStatus;
        return checktlsStatus;
    }
}

我不确定你想做什么。所以只需将

checkTLS
重新制作为异步函数即可。


如果您不需要,我建议使用

fs.promises
async/await
。试试这个:

const fs = require("fs");

params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

Object.keys(params).forEach( key => {
    console.log(key);
    if(key.includes("tls")){ 
        //splitting parms to get cluster id
        clusterId=key.substring(0, key.indexOf("_"));
        console.log("cluster ID=="+clusterId);
        // this changed
        checkTLS(clusterId)
            .then(tlsresult => {
                console.log("tls result is="+ tlsresult);
                // req.body[`${clusterId}_tls`]=tlsresult;
                // console.log(req.body.ibmdev_tls);
                console.log("==================================");
            });
    }
});

function checkTLS(clusterID){
    return new Promise(resolve => {
        fs.readFile("clusterinfo/clusterinfo.json",(err, clusters) => {
            TlsVerion="TLS12";
            if(TlsVerion.includes("TLS12")){ 
                console.log(`TLs check status ------------------------ for ${clusterID}`);
                console.log(` TLS match the Security Baseline requirement for ${clusterID}`);
                checktlsStatus="implemented";
                //req.body.ibmdevtls=tlsStatus;
                //return console.log(checktlsStatur+ "check for tls succeeded");
                // req.body.(`${clusterID}`+`tls`)=tlsStatus;
                resolve(checktlsStatus);
            }
        });
    });
}

参考资料:


0
投票

我已经使用异步和等待修改了具有相同功能的代码。 Contents 变量具有读取文件的内容。

    const fs = require('fs')
    const util = require('util')`enter code here`
    const readFileContent = util.promisify(fs.readFile)
    const fetchFile = async (path,clusterID) => {
    const buff = await readFileContent(path)

    const contents = buff.toString()
    TlsVerion="TLS12";
    if(TlsVerion.includes("TLS12")){ 
          console.log(`TLs check status ------------------------ for ${clusterID}`);
          console.log(` TLs match the Secuity Baseline requirment for ${clusterID}`);
          checktlsStatus="implemented";
          return checktlsStatus;
      }
      console.log(`\nContents of the file :`)
    }
       

    async function neo(){
        params={ibmdev_tls: 'not imp',ibmqa_tls: 'not imp',ibmqa_ssl: 'not imp'}  

        for (const property in params) {
            console.log(property);
            if(property.includes("tls")){ 
                //splitting parms to get cluster id
                clusterId=property.substring(0, property.indexOf("_"));
                console.log("cluster ID=="+clusterId);
                tlsresualt = await fetchFile('file.json',clusterId);
                console.log("tls resualt is="+ tlsresualt);
                console.log("==================================");
        }
        }
    }


    neo()

参考这里。您可以参考相同的详细解释

© www.soinside.com 2019 - 2024. All rights reserved.