我们如何从JS文件中导出解决的承诺?
我必须从 Javascript 文件导出 async
函数的结果。现在,当我导出它时,我得到了一个承诺,无论我们想要导入该文件,每个文件中都需要 then()
函数。由于这个问题,我需要在导入它的每个文件中解析导出的结果。我只是想要异步操作的结果而不是承诺。我们怎样才能实现它呢?
mainfile.js
const getAllDatabases = async(dbconnection) => {
const results = await dbconnection.query(
`SELECT name FROM master.dbo.sysdatabases`
);
return results;
}
module.exports = getAllDatabases();
otherfile.js
const mainfile = require("mainfile");
mainfile.then((reponse)=>{
reponse[db].Table.Operation();
});
I have to export a result of async
function from a Javascript file. Right now, When I export it, I am getting a promise which needs then()
function in each file wherever we want to import that file. Due to this issue, I need to resolve the exported results in each file where we are importing it. I simply want the results of the async
operation not the promises. How can we achieve it ?
mainfile.js
const getAllDatabases = async(dbconnection) => {
const results = await dbconnection.query(
`SELECT name FROM master.dbo.sysdatabases`
);
return results;
}
module.exports = getAllDatabases();
otherfile.js
const mainfile = require("mainfile");
mainfile.then((reponse)=>{
reponse[db].Table.Operation();
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能用 CommonJS(你现在使用的)做到这一点。您可以很好地导出承诺,但是使用该导出的任何内容都必须 使用承诺(这不是“解决”它,解决是另一回事;我写了一些术语此处)。在一般情况下,这应该没问题,这不像您正在重新运行流程或其他任何内容,您只是在访问承诺已经具有的履行值。或者,您可以导出一个对象(嗯,一个不同的对象)并填写名称作为该对象的属性,但使用该对象的任何代码都必须考虑到它尚未填写的可能性。这就是承诺的全部要点:标准化这样的情况。
通过 ESM,您可以使用顶级
await
,它具有良好的浏览器支持、Node.js 支持以及大多数现代捆绑程序的支持。这可以让您暂停模块的加载,直到异步过程完成,从而允许您导出获得的值:mainfile.js
在实现该承诺之前不会完成加载(并且不会)如果承诺被拒绝,则根本不会完成;您可以使用try
/catch
来处理。You can't do that with CommonJS (what you're using now). You can export the promise just fine, but anything using that export has to consume the promise (that's not "resolving" it, resolving is a different thing; I've written up some terminology here). That should be fine in the general case, it's not like you're re-running a process or anything, you're just accessing the fulfillment value the promise already has. Alternatively, you could export an object (well, a different object) and fill in the names as properties on that object, but any code using the object would have to allow for the possibility it's not filled in yet. Which is the whole point of promises: to standardize situations like that.
With ESM, you can use top-level
await
, which has good browser support, support in Node.js, and support in most modern bundlers. That would let you hold up the loading of your module until the asynchronous process completes, allowing you to export the value you got:mainfile.js
doesn't finish loading until that promise is fulfilled (and doesn't finish at all if the promise is rejected; you could handle that with atry
/catch
).