繁体   English   中英

使用tablesasjson调用函数后如何更改变量的值?

[英]how to change the value of variable after calling the function using tablesasjson?

为什么调用函数后变量不能改变?

这是我的代码:

const tabletojson = require('tabletojson');

var email ;

tabletojson.convertUrl(

    'https://myurl
    ,
    { stripHtmlFromCells: true },
    function(tablesAsJson) {


  email = tablesAsJson[2][7][1];
var result2 = tablesAsJson;
        console.log(result2);
        var Firstname;
        var lastname;
        Firstname = tablesAsJson[0][1][1]
        lastname = tablesAsJson[0][0][1]

        console.log("Hello Sir: "+Firstname + "  " +lastname + ".  your email is : " + email)

        console.log(email)// this prints the correct answer
    }
  );

在尝试在函数范围外打印电子邮件时,它返回一个空白文本,console.log("the email is " + email);

如果您需要将此代码用作模块的导出函数,则需要如下内容:

测试模块.js:

'use strict';

const tabletojson = require('tabletojson');

async function getTableAsArray(url) {
  try {
    return await tabletojson.convertUrl(url);
  } catch (err) {
    console.error(err);
  }
}

module.exports = {
  getTableAsArray,
};

测试.js:

'use strict';

const testModule = require('./test-module.js');

(async function main() {
  try {
    const array = await testModule.getTableAsArray(
      'https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes'
    );
    console.log(array[1][0]);
  } catch (err) {
    console.error(err);
  }
})();

方法 convertUrl 是异步的,您不能随意在顶级代码中使用像await

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM