Home > Blockchain >  How can I return an array from a promise to use in an Expo / React Native app?
How can I return an array from a promise to use in an Expo / React Native app?

Time:02-24

I'm trying to create an app with routing capabilities and for this, I need to use the OpenRouteService-JS API. The way I have this set up is, what I assume to be, in a promise.

I can't get the array out of the promise, I've tried using an async function with await but that seems to be returning nothing and I don't know if the promise is set up wrong or the async function is set up wrong.

Here is the promise :

function getRoute() {
    var openrouteservice = require("openrouteservice-js");
    var Directions = new openrouteservice.Directions({ api_key: "######"});

    // Direction Request
    Directions.calculate({
        coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
        profile: 'foot-walking',
        extra_info: ['waytype', 'steepness'],
        format: 'geojson'
    })
        .then(function(geojson) {
            // Add your own result handling here
            var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
            console.log(PolyLine);
            return PolyLine
        })
        .catch(function(err) {
            var str = "An error occurred: "   err;
            console.log(str);
        });
}

Here is how I'm trying to collect it:

React.useEffect(() => {
        async function getPolyLine() {
            const res = await getRoute(); // type: Promise<Interface>
            console.log(res)
            setPolyLine(res);
        }

        getPolyLine();
    }, [])
    const [polyline, setPolyLine] = React.useState()

I have no real experience with Javascript or React and promises have been an interesting problem to stumble upon.

CodePudding user response:

You need to add a return statement like this:

function getRoute() {
    var openrouteservice = require("openrouteservice-js");
    var Directions = new openrouteservice.Directions({ api_key: "######"});

    // Direction Request
    return Directions.calculate({
        coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
        profile: 'foot-walking',
        extra_info: ['waytype', 'steepness'],
        format: 'geojson'
    })
        .then(function(geojson) {
            // Add your own result handling here
            var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
            console.log(PolyLine);
            return PolyLine
        })
        .catch(function(err) {
            var str = "An error occurred: "   err;
            console.log(str);
        });
}

So in your code you aren't actually returning the promise.

CodePudding user response:

I think here we have to create our custom Promise and resolve it with possible values to return a value to our desired statement.

As herein JavaScript, we cannot return statements directly from inner functions as you tried in the then clause.

Have a try with the following changes, Hope it will solve your problem:

function getRoute() {
    var openrouteservice = require("openrouteservice-js");
    var Directions = new openrouteservice.Directions({ api_key: "######"});

    return new Promise((resolve, reject) => {
        // Direction Request
        Directions.calculate({
            coordinates: [[8.690958, 49.404662], [8.687868, 49.390139]],
            profile: 'foot-walking',
            extra_info: ['waytype', 'steepness'],
            format: 'geojson'
        })
            .then(function(geojson) {
                // Add your own result handling here
                var PolyLine = geojson.features[0].geometry.coordinates.map(c => ({latitude: c[0], longitude: c[1]}))
                console.log(PolyLine);
                resolve(PolyLine)
            })
            .catch(function(err) {
                var str = "An error occurred: "   err;
                console.log(str);
                resolve([])
            });
    })
}
  • Related