简体   繁体   中英

Get value returned from Promise in JavaScript

I´m new to JavaScript and a little bit confused about Promise s, 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?

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);
        });
    });
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM