【问题标题】:how to change the value of variable after calling the function using tablesasjson?使用tablesasjson调用函数后如何更改变量的值?
【发布时间】:2019-06-15 00:12:35
【问题描述】:

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

这是我的代码:

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("邮箱是" + email);

【问题讨论】:

    标签: javascript node.js json npm


    【解决方案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,
    };
    

    test.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);
      }
    })();
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 知道怎么做吗?用你的方法我得到'等待只在异步函数中有效'
      • 我认为你只能在回调或 Promise(...).then(...) 中读取值
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2011-03-23
      相关资源
      最近更新 更多