简体   繁体   English

调用函数是调用promise函数并将结果返回给原始函数的JavaScript

[英]Call a function is JavaScript that calls a promise function and returns the result to the original function

I have two functions (One function within the controller and oen function in a service).我有两个功能(控制器中的一个功能和服务中的 oen 功能)。 I want to call the service function from the controller function.我想从控制器功能调用服务功能。 After calling teh service function this function calls a database function (using Sequelize).调用服务函数后,此函数调用数据库函数(使用 Sequelize)。

Controller:控制器:

exports.getMilestoneById = async (req, res, next) => {
    const milestoneId = req.params.milestoneId;
    try{
    milestoneService.getMilestoneById(milestoneId)
    .then(mielstone => {
        console.log("Milestone in tehn: " + mielstone)
    });
    console.log("Milestone: " + milestone);
    res.status(200).json({message: 'Milestone fetched', milestone: milestone});
    } catch (error){
        if (!error.statusCode){
            error.statusCode = 500;
        }
    }
}

Service:服务:

exports.getMilestoneById = async (milestoneId) => {

Milestone.findByPk(milestoneId)
.then(milestone => {
    console.log("In Service: " + milestone)
    return milestone.get();
})
.catch(err => {
    console.log("Error" + err);
});

} }

The problem: I don't get a milestone back.问题:我没有得到一个里程碑。

Ok, let's try to put some order here.好的,让我们尝试在这里下订单。

Promises Flow承诺流

Your code doesn't wait for the Promise response.您的代码不会等待Promise响应。

milestoneService.getMilestoneById(milestoneId) // <- this returns a promise
// all stuff below here doesn't wait for the promise to complete and can't see its result
console.log("Milestone: " + milestone);
res.status(200).json({message: 'Milestone fetched', milestone: milestone});

Instead, writing something like:相反,编写如下内容:

milestoneService.getMilestoneById(milestoneId)
    .then(mielstone => {
        console.log("Milestone in tehn: " + mielstone);
        // I moved all the stuff that needs to wait in here!!
        console.log("Milestone: " + milestone);
        res.status(200).json({message: 'Milestone fetched', milestone: milestone});
    });

This would work as expected.这将按预期工作。

Async / Await异步/等待

You added that async before the functions, I'd figure you could put that to good use!你在函数之前添加了async ,我想你可以好好利用它! async / await helps you clean the promises flow by letting the wrapping function wait for their results, so writing something like: async / await通过让包装函数等待其结果来帮助您清理 Promise 流,因此编写如下内容:

    const milestone = await milestoneService.getMilestoneById(milestoneId)
    console.log("Milestone: " + milestone);
    res.status(200).json({message: 'Milestone fetched', milestone: milestone});

Would also work as expected.也会按预期工作。

Returns退货

... or not! ... 或不! You missed pretty much all returns in your code.您几乎错过了代码中的所有返回。 As a rule of thumbs try to make every function always return something, especially if it's promises!作为一个经验法则,尽量让每个函数总是返回一些东西,特别是如果它是承诺的! So like:就像:

exports.getMilestoneById = async (milestoneId) => {
 const milestone = await Milestone.findByPk(milestoneId);
 return milestone.get();
 /* I don't suggest handling the error here, because it doesn't bubble well! 
 /* If there's an error what would this function return?
}

Then然后

exports.getMilestoneById = async (req, res, next) => {
    const milestoneId = req.params.milestoneId;
    try {
       const milestone = await milestoneService.getMilestoneById(milestoneId)
       console.log("Milestone: " + milestone);
        // just return this
       return res.status(200).json({ message: 'Milestone fetched', milestone });
    } catch (error){
        if (!error.statusCode){
            error.statusCode = 500;
        }
        // call next with the error!
        return next(error);
    }
}

When you are returning the result in this callback:当您在此回调中返回结果时:

.then(milestone => {
    console.log("In Service: " + milestone)
    return milestone.get();
})

You are in fact setting the return value for the callback function, not the return value for your service function milestone service.getMilestoneById() .您实际上是在设置回调函数的返回值,而不是您的服务函数milestone service.getMilestoneById()的返回值。 Because your function is an async function, you should use Javascript's async-await syntax, which will only get the value once the promise is resolved.因为你的函数是一个async函数,你应该使用 Javascript 的 async-await 语法,它只会在 promise 被解决后才获取值。

exports.getMilestoneById = async (milestoneId) => {
    const milestone = await Milestone.findByPk(milestoneId)
    .catch(err => {
        console.log("Error" + err);
    });

    console.log("In Service: " + milestone)
    return milestone
}

This should be the same for your controller function:这对于您的控制器功能应该是相同的:

exports.getMilestoneById = async (req, res, next) => {
    const milestoneId = req.params.milestoneId;
    try{
    const milestone = await milestoneService.getMilestoneById(milestoneId)
    console.log("Milestone: " + milestone);
    res.status(200).json({message: 'Milestone fetched', milestone: 
    milestone});
    } catch (error){
        if (!error.statusCode){
            error.statusCode = 500;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM