0

I would have a simple question but can't figure it out the answer with Node.JS. Here it is : I got a file with multiple function and I would like to use the return of the first inside the second :

//The first function
const Function1 = (req, res) => {
    var axios = require('axios');
    var config = {
        method: 'get',
        url: 'xxxxx.json',
        headers: {
            //...
        }
    };
    axios(config).then(function(response) {
        const array = response.data.datas
        return Promise.all(Object.values(array).map(entry => {
            return entry.id
        }))
    }).then(function(response) {
        //I got an array with infos
        return response
    }).catch(function(error) {
        console.log(error);
    });
}
const Function2 = (req, res) => {
    const previousResult = function1()
    //Undefined
    console.log(previousResult)
}

How should I proceed ?

Thanks a lot

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Arthur Fortin
  • 103
  • 1
  • 10

1 Answers1

0

Do you need to call the function?

function1()

Update:

It looks like you added to your question. This now seems to be an issue with async functions. You should look up how to use promises, and async await. It's a bit too complex to describe here, and there are a lot of tutorials about it. The short answer is that when you return inside of a promise, it doesn't return from the outer function1. You could probably test this in your code by putting an explicit return at the end of function1 and you'll see that in console.log().

pixelearth
  • 13,674
  • 10
  • 62
  • 110