控制台语句不等待 javascript 中的函数 return

Console statment not waiting for the function return in javascript

我正在尝试将变量 x 初始化为 showData 函数返回的值。这是我的代码:

app.post("/view/show", (req,res) => {
    let x = showData(req.body.custmerName);
    console.log(x);
}

这里是 showData 函数:

const showData = (custName) => {
    const customer = mongoose.model(custName ,collectionSchema,custName);
    customer.find( (error,data) => {
        if (error){
            console.log(error);
        }else{
            return data;  
        }
    });
}

然而,控制台显示undefined。如果我将 console.log(data) 添加到 showData 函数,我可以看到我能够成功地从数据库中获取数据。

我了解到 console.log(x) 没有等待 showData() 的执行,因为 JavaScript 是同步的 属性。如何从函数中获取值并将其记录到控制台,而不是获取 undefined?

您需要一个异步函数来执行此操作。执行以下操作:

app.post("/view/show", async(req,res) => {
    let x = await showData(req.body.custmerName);
    console.log(x);
}

处理异步函数时可以使用async/await或回调。

app.post("/view/show", (req,res) => {
  showData(req.body.custmerName, (err, res) => {
    const x = res;
    console.log(x);
  });
});

const showData = (custName, callback) => {
  const customer = mongoose.model(custName ,collectionSchema,custName);
  customer.find(callback);
}

我以前没有实际使用过 Mongoose,但是查看文档,似乎没有一个只接受回调函数的 find 函数版本。

也尝试传递查询对象(在您的情况下,一个空对象就足够了):

customer.find({}, (error,data) => {
    if (error) {
        console.log(error);
    } else {
        return data;  
    }
});

来自文档:

// find all documents
await MyModel.find({});

// find all documents named john and at least 18
await MyModel.find({ name: 'john', age: { $gte: 18 } }).exec();

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
await MyModel.find({ name: /john/i }, 'name friends').exec();

// passing options
await MyModel.find({ name: /john/i }, null, { skip: 10 }).exec();