Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
How can I return an array from a promise to use in an Expo / React Native app?

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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([])
            });
    })
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda