0 votes
1 view
in Web Technology by (11.2k points)

I have a async function in controller which should await on another service function returning value, but it's not waiting on it. If only one (or the best) way to resolve this problem is to return new Promise despite just value? Controller code

exports.trip = async (req, res, next) => {

try {

    let result = await osrmService.trip(req.body.options);

    console.log(result) //result is undefined

    res.status(200).json({

        route: result

    });

} catch (error) {

    next(error)

}

osrmService code: (not waiting for value)

exports.trip = async (options) => {

osrm.trip(options, await function(err, result) {

    if (err) throw err;

    //console.log(result)

    return result;

});

I did it in this way and its working correctly:

exports.trip = (options) => {

return new Promise((resolve, reject) => {

    osrm.trip(options, function (err, result) {

        if (err) reject(err);

        resolve(result)

    });

});

Is it the optimal way?

1 Answer

0 votes
by (22.1k points)

You need to use a promise to return the value and resolve that before returning it to main function.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...