CIOC
CIOC

Reputation: 1407

Get value returned from Promise in JavaScript

I´m new to JavaScript and a little bit confused about Promises, this is what I have:

export const testFunction = () => dispatch => {
    otherFunction().then(( response ) => {
        //do something...
        return response;
    }).catch(( error ) => {
        //do something...
        return error;
    });
}

In another file I'm trying to get the value returned from the then like this:

let result = this.props.testFunction()

And like this:

let result = this.props.testFunction ().then(( result ) => {
  console.log(result);
}).catch(( error ) => {
  console.log(result); // undefined
});

But I get undefined as the result, what is the correct way of getting that value?

Upvotes: 0

Views: 59

Answers (2)

Kubwimana Adrien
Kubwimana Adrien

Reputation: 2531

testFunction is not returning a Promise so you can't use then or catch and returns undefined because well, it's not returning any thing. Try to return a promise like the example below however I am not sure what the dispatch argument supposed to do so I have removed it and hopefully this'll help:

export const testFunction = () => {
    return new Promise((resolve, reject) => {
        otherFunction().then(( response ) => {
            //do something...
            resolve(response);
        }).catch(( error ) => {
            //do something...
            reject(error);
        });
    });
}

Upvotes: 1

Ramsés Ariel
Ramsés Ariel

Reputation: 1

when you are trying to return a promise to use it in another file, you must use the following syntax:

const testFunction = () => {
    return new Promise((resolve, reject) => {
        if (error) {
            return reject(error); // this is the value sent to .catch(error)
        }
        return resolve(valueToReturn); // this is the value sent to .then(result)
    });
}

This is how you create a promise to use where you want, if it has an error it will sent to catch block, otherwise you should see the console.log(result) value.

And in your external file you can use the syntax that you are using, try it in that way to see the console.log value.

Here is a link to see more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Upvotes: 0

Related Questions