1

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

这是我的代码:

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);

4

2 回答 2

1

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

测试模块.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);
  }
})();
于 2019-01-25T13:32:07.403 回答
0

方法 convertUrl 是异步的,你不能在顶层代码中随意使用await 。

于 2019-01-21T16:18:59.237 回答