简体   繁体   English

NodeJs:如何将异步值导出到另一个文件?

[英]NodeJs: How to export an async value to another file?

I'm trying to access the result from an async function from one file in another file (say index.js). 我正在尝试从另一个文件中的一个文件(例如index.js)访问异步函数的结果。

test.js test.js

const preMovie = async () => {
    const promiseTickets = new Promise((resolve, reject) => {
        console.log("abcde");
        resolve('ticket is here')
    });

    let ticket = await promiseTickets;
    return ticket;
}

preMovie().then((m) => console.log(m));

index.js index.js

//access the value of ticket here

My goal is to export the value inside ticket only when it has completed its task. 我的目标是仅在完成任务后才导出票证中的值。 I don't want to export an undefined value. 我不想导出未定义的值。 I have tried my hand with different solutions, but either they are too complicated for me to understand or didn't blend with what I was looking for. 我尝试了不同的解决方案,但是它们要么太复杂以至于我无法理解,要么没有与我所寻找的融合。

You can export a Promise that resolves to ticket 's value: 您可以导出解决ticket价值的Promise:

 // test.js const preMovie = async () => { const promiseTickets = new Promise((resolve, reject) => { console.log("abcde"); resolve('ticket is here') }); let ticket = await promiseTickets; return ticket; } const moviePromise = preMovie(); //export default moviePromise; // main.js //import moviePromise from './test.js'; moviePromise .then(ticket => console.log(ticket)); 

Uncomment the import and export statements when using them in your actual code, of course. 当然,在实际代码中使用importexport语句时,请取消注释。 Another option would be to export the function itself, calling it and calling .then on it, if there's a possibility of the function being needed to be called more than once, or if controlling its timing is important. 另一种选择是导出的函数本身,调用它,并调用.then就可以了,如果有被称为不止一次,或者控制其时机是非常重要的被需要的功能的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM