在另一个文件中控制异步功能

时间:2019-05-31 16:02:10

标签: javascript mongodb mongoose

我正在调用名为feedFactory的文件中的另一个函数,该函数具有一个异步调用School.findOne,该调用返回一个Promise。因此,以下get postFields值为null,因为它不等待。如何从调用函数feedFactory.BuildPostBody的文件中控制异步流?

const postFields = feedFactory.BuildPostBody(req, res, errorResponse);

然后在文件中 feedFactory 我有以下代码块,可在执行查询后返回promise。

      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 

              ...

1 个答案:

答案 0 :(得分:2)

您可以使用Async / await完成您的目标:

将此代码放入async函数中,并更改为:

const postFields = await feedFactory.BuildPostBody(...)

然后使用postFields

postFields.then(...)