Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何从then()导出值?_Node.js - Fatal编程技术网

Node.js 如何从then()导出值?

Node.js 如何从then()导出值?,node.js,Node.js,我想在模块中包含以下js: const fs = require('fs'); const got = require('got'); const jsdom = require("jsdom"); const { JSDOM } = jsdom; const vgmUrl = 'https://example.com/somehtml.html'; got(vgmUrl).then(response => { var dom = new JSDOM(re

我想在模块中包含以下js:

const fs = require('fs');
const got = require('got');
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

const vgmUrl = 'https://example.com/somehtml.html';


got(vgmUrl).then(response => {
    var dom = new JSDOM(response.body);
    var textContent = dom.window.document.getElementById("__NEXT_DATA__").textContent;
    var JSONData = JSON.parse(textContent);
    return JSONData.props.pageProps.text.vaccinaties.data.kpi_total.tab_total_estimated.value;
}).then(out => {
    //console.log(out);
    module.exports = out;
});
当我使用以下方法将其包括在内时:

const module = require('./module.js');
然后使用console.logmodule;它返回一个空对象{}


那么,如何在上一个模块中导出变量“out”的值呢?

我以前遇到过这个问题,发现如果模块中有异步函数,我就无法导出“real”对象,我不能在模块的顶层使用wait,也不能像您那样在函数中导出。因此,解决方案具有javascript的特性。您必须导出对象或异步函数的承诺,就像Georgi B.Nikolov在评论中提到的那样。

Node.js构建在异步调用之上。在你的情况下,我会这样做

const fs = require('fs');
const got = require('got');
const jsdom = require("jsdom");
const {JSDOM} = jsdom;

const vgmUrl = 'https://example.com/somehtml.html';

let outData = null;

const requestsCallbacks = [];


got(vgmUrl).then(response => {
    var dom = new JSDOM(response.body);
    var textContent = dom.window.document.getElementById("__NEXT_DATA__").textContent;
    var JSONData = JSON.parse(textContent);
    return         JSONData.props.pageProps.text.vaccinaties.data.kpi_total.tab_total_estimated.value;
}).then(out => {
    //console.log(out);
    outData = out;
    requestsCallbacks.forEach(cb => cb(out));
});

module.exports = () => {

    // If out data is already available just return it
    if (outData) {    
        return outData;
    }

    // Store all requests to return outData when available
    return new Promise(resolve => {
        requestsCallbacks.push(resolve);
    });

}
当您需要使用它时:

const module = require('./module.js');
async function doSomething() {
   const data = await module();
}

为什么要这样导出?为什么不直接导出承诺,在你需要的地方导入,然后再做一个呢?编辑:您可以保持当前文件的原样。导入并调用后,参数将是返回值JSON.props。。。等等,我如何使用函数doSomething的数据?当我向doSomething添加返回数据时,它返回Promise{}。请原谅我,我是一个彻头彻尾的noob。最简单的方法是声明异步函数并等待promise返回值,如我的示例所示。下面是异步/等待工作原理的一个很好的解释。