簡體   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