[英]Setting up async await function order
i have tow functions both are async.我有两个功能都是异步的。 i want to make sure one is executed after another the following code is within async
我想确保一个接一个执行以下代码在异步中
const user= await User.find({
_id: req.user.id
});
const userName= `my user name is ${user.userName}`;
const email= `my email is ${user.email}`;
const {response} = await printUser({userName,email};
The problem is the printUser function is executed before im finding the user so the values of userName and email are undefined.问题是在找到用户之前执行了 printUser 函数,因此 userName 和 email 的值未定义。
NOTE: the following code is in express router and the find function is working (returing the user)注意:以下代码在快速路由器中并且查找功能正在工作(返回用户)
I'm assuming all of these lines of code are inside an async function as well.我假设所有这些代码行也在异步函数中。
Your problem is that find
returns an Array of users and not a single user, change您的问题是
find
返回一个用户数组而不是单个用户,请更改
const user= await User.find({
_id: req.user.id
});
To:到:
const user= await User.findOne({
_id: req.user.id
});
If the code is not within a function but in the main file, then yea you're going to have to use callbacks.如果代码不在函数中而是在主文件中,那么是的,您将不得不使用回调。
You need to use callbacks.您需要使用回调。 Something like below:
像下面这样:
User.find({
_id: req.user.id
}, function (user) {
printUser(user.userName, user.email);
});
Assuming you are mongoose which doesn't return promise for query functions (Read here - https://mongoosejs.com/docs/promises.html#queries-are-not-promises ).假设您是猫鼬,它不会返回查询功能的承诺(阅读此处 - https://mongoosejs.com/docs/promises.html#queries-are-not-promises )。 You can either use
.then
or use .exec
which will return a proper promise.您可以使用
.then
或用.exec
将返回一个适当的承诺。 something like就像是
const user = await (User.find({
_id: req.user.id
})).exec();
const userName= `my user name is ${user.userName}`;
const email= `my email is ${user.email}`;
const {response} = await printUser({userName,email};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.