JavaScript-Async/Await-如何从嵌套函数返回结果



我是Node.js的新手,很难处理async/await模型。我遇到的问题是,嵌套函数调用在异步/等待方法中返回数据,我总是得到'undefined'。我的功能结构如下:

const findCustomerOrder = async (id) => {
const orders = await Order.find({custoemrId:id})
.then(async (order) => {
if(order)
{
const products = await findProductsByOrderId(order._id)
.then(async (result) => {
for(const r in result){
console.log("Product ID: ", result._id);
}
});
}
else
console.log("order not found");     
});
}
const findProductsByOrderId = async (id) => {
try{
const products = await Products.find({orderId:id}, (error, data) => {
if(error) console.log(error);
else 
return data;
});
}
catch(err){
return 'error!!';
}
}

我知道,如果顶级调用是async/await,那么所有嵌套调用都应该像我尝试的那样等待

我在这里做错了什么?

去掉所有then,也去掉DB查询中的回调。仅使用await。这将使整个代码更容易推理,而且作为重组的一部分,它也应该解决您的问题。

在下面的例子中,我还在订单上添加了一个循环,因为您正在获取所有订单,作为数组,但随后您的代码表现得好像只获取了一个订单。我还修复了产品循环。

然而,你获取产品的方式似乎无论如何都不正确,请参阅我在下面的评论。我没有修复它,因为我不知道你的数据库结构看起来怎么样,所以我不知道正确的方法是什么

async function findCustomerOrder (id) {
const orders = await Order.find({ customerId: id })

for (const order of orders) {
console.log(`Order ID: ${order._id}`)

const products = await findProductsByOrderId(order._id)
for (const product of products) {
console.log(`Product ID: ${product._id}`);
}
}
}
async function findProductsByOrderId (id) {
// Note: I don't think this is right. It seems to find all
// products with the given ID - which will always be one -
// and that ID would be the _product_ ID and not the order ID.
return await Products.find({ _id: id })
}

先发制人的评论回复:return await是故意的,这就是为什么

您应该删除then和回调,然后可以执行下面的

const findCustomerOrder = async(id) => {
try {
const orders = await Order.find({
custoemrId: id
});
if (orders) {
let promiseArray = [];
orders.forEach(order => {
promiseArray.push(findProductsByOrderId(order._id));
});
let results = await Promise.all(promiseArray);
return results;
}
return "order not found";
} catch (err) {
throw err;
}
}
const findProductsByOrderId = async(id) => {
try {
const products = await Products.find({
_id: id
});
return products;
} catch (err) {
throw err;
}
}

最新更新