I am calling another function in a file called feedFactory
, the function has a asynchronous call, School.findOne
, that returns a promise. So the following get postFields
value is null since it doesn't wait. How can I control the asynchronous flow from the file that calls the function feedFactory.BuildPostBody
?
const postFields = feedFactory.BuildPostBody(req, res, errorResponse);
And the in the file feedFactory
I have the following block of code that returns a promise after I do a query.
exports = module.exports = {
BuildPostBody: (req, res, errorResponse) => {
//Determine what account type we are going to post as using field
//postToFeedAs
let postFields;
case "School":
{
//Get industry partner name and company logo
School.findOne({ _id: req.user.school }).then(school => {
let avatar =
"https://image.png";
if (typeof school.profile.school_logo !== "undefined") {
avatar = school.profile.school_logo.url;
}
postFields = {
author: {
userType: req.body.postToFeedAs,
user: req.user.school,
name: school.name,
avatar: avatar
},
postType: "text",
postBody: req.body.postBody
};
console.log("returning post back from factory");
return postFields; <--Returns late
...
You can use Async/await to accomplish your goal:
Put this code into an async
function and change to:
const postFields = await feedFactory.BuildPostBody(...)
then when using postFields
do
postFields.then(...)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.