我在名为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

              ...

最佳答案

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

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

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

然后在使用postFields

postFields.then(...)

08-19 19:41