Javascript 无法将模块下的异步函数导出到其他文件
我正在从事一个项目,其中我的所有文件都以json对象表示法表示,我在一个对象下声明了一个异步函数,我想将该函数从特定文件导出到另一个文件。该文件称为test2.js 代码为:-Javascript 无法将模块下的异步函数导出到其他文件,javascript,node.js,asynchronous,import,export,Javascript,Node.js,Asynchronous,Import,Export,我正在从事一个项目,其中我的所有文件都以json对象表示法表示,我在一个对象下声明了一个异步函数,我想将该函数从特定文件导出到另一个文件。该文件称为test2.js 代码为:- const puppeteer = require('puppeteer') const test={ browser:null, page:null, initial:async () => { test.browser = await puppeteer.launch({
const puppeteer = require('puppeteer')
const test={
browser:null,
page:null,
initial:async () => {
test.browser = await puppeteer.launch({headless:false});
test.page = await test.browser.newPage();
await test.page.goto('https://www.safari.com/');
// await page.screenshot({path: 'example.png'});
async function dostuff(){
let h1;
try{
h1=await test.page.evaluate(()=>{
let h = document.querySelector('h1').innerText;
return {
h
}
});
let heading = h1.h
return heading;
}catch(err){
return `Sorry the value is not been permited`
}
}
//const h = Promise.resolve(dostuff()).then(head =>console.log(head))
//this is working fine
// Promise.resolve(dostuff()).then(head =>console.log(head))
await dostuff()
},
}
module.exports = test //Here I don't kind of know how to call the function as with module.exports.dostuff = this.dostuff is also not working ...
我想在名为test_result.js的第二个文件上调用此函数
这就像:
const helper = require('./test2')
async function node(){
await helper.initial()
await Promise.resolve(helper.dostuff()).then(head =>console.log(head))
}
node()
运行时代码中的错误是“helper.dostuff”不是函数
关于如何在指定时间或在运行时运行代码以从元素获取数据的任何想法,helper.dostuff不是函数错误,正在由解决
module.exports.dostuff = this.dostuff
但是
在test_result.js上,文件显示未定义
不知道如何及时解决此问题。helper.dostuff不是一个函数错误,正在由解决
module.exports.dostuff = this.dostuff
但是
在test_result.js上,文件显示未定义
不知道如何及时解决此问题请尝试以下方法:-
导出测试对象@test2.js:
export const test = { //your code with 'initial' method/prop };
导入测试对象@test_result.js:
import { test } from './filepath_of_test2.js'
async someFunction = () => {
await test.initial();
}
someFunction();
函数调用/执行@test_result.js:
import { test } from './filepath_of_test2.js'
async someFunction = () => {
await test.initial();
}
someFunction();
试试这个:-
导出测试对象@test2.js:
export const test = { //your code with 'initial' method/prop };
导入测试对象@test_result.js:
import { test } from './filepath_of_test2.js'
async someFunction = () => {
await test.initial();
}
someFunction();
函数调用/执行@test_result.js:
import { test } from './filepath_of_test2.js'
async someFunction = () => {
await test.initial();
}
someFunction();
您在
initial()
中定义了doStuff
,而不是作为test
对象的一部分,因此找不到它。正确的缩进将有所帮助。您在initial()
中定义了doStuff
,而不是作为test
对象的一部分,这就是为什么找不到它的原因。适当的缩进会有帮助。