【发布时间】:2021-06-02 14:01:32
【问题描述】:
所以我一直在摆弄javascript,发现了一个奇怪的行为,反正现在。
鉴于这些 sn-ps
database.js
import MongoDB from "mongodb";
const MongoClient = MongoDB.MongoClient;
const uri = "mongodb://127.0.0.1:27017/?poolSize=20&writeConcern=majority"
const mongoClient = new MongoClient(uri, { useUnifiedTopology: true });
let instance;
const getInstance = async () => {
if (!instance) {
instance = mongoClient.connect();
}
return instance;
}
export const client = await getInstance();
services.js
import { client } from "./database"
//return array of items
function getUserRecommendationItems(username) {
const shopifyDb = client.db('Shopify');
const product = shopifyDb.collection('product');
return product.find().toArray();
}
export default { getUserRecommendationItems }
index.js
import services from "./services"
(async () => {
const products = await services.getUserRecommendationItems();
console.log(products);
})();
当我删除 database.js 中的 await 时,它会抛出一个错误,因为它需要等待客户端首先连接。
我的问题是,为什么我可以在 service.js 中访问 client 而无需将其放入异步函数中?
这是否意味着导出和导入是底层的异步函数?
【问题讨论】:
-
据我了解,您已经从 database.js 中导出了已履行的承诺(客户端)。因此,当您在 service.js 中访问客户端时,您正在使用该对象。另外,您在问题中添加 index.js 的原因是什么?描述中没有。
-
@TusharShahi 感谢您的回复,我添加 index.js 只是为了让我的问题完全符合上下文,但仍然留下了主要问题。我试图在 getInstance 函数中移动 await ,但我得到了
client.db is not a function错误。这又很奇怪,因为mongoClient.connect()是一个承诺,它应该有效。 -
“我得到 client.db 不是函数错误。这又很奇怪” - 异步函数返回一个承诺 - 当你删除 @987654331 之前的
await@ 函数,您正在导出处于待处理状态的承诺。您需要await客户端或链接then方法调用以使用它所实现的值。在待处理的 promise 上调用db方法是导致错误的原因。
标签: javascript node.js mongodb asynchronous