gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:00:28 25 4
gpt4 key购买 nike

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

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

并且在文件中饲料工厂我有以下代码块,在我执行查询后返回一个 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(...)

关于javascript - 在另一个文件中控制异步功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398392/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com