繁体   English   中英

获取从 JavaScript 中的 Promise 返回的值

[英]Get value returned from Promise in JavaScript

我是 JavaScript 的新手,对Promise有点困惑,这就是我所拥有的:

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

在另一个文件中,我试图获取从then返回的值,如下所示:

let result = this.props.testFunction()

像这样:

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

但是我得到undefinedresult ,获得该值的正确方法是什么?

testFunction没有返回 Promise 所以你不能使用thencatch并返回undefined因为好吧,它没有返回任何东西。 尝试像下面的示例一样返回 promise 但是我不确定 dispatch 参数应该做什么,所以我已经删除了它,希望这会有所帮助:

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

当您尝试返回 promise 以在另一个文件中使用它时,您必须使用以下语法:

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

这就是您创建 promise 以在您想要的地方使用的方式,如果它有错误,它将发送到 catch 块,否则您应该看到 console.log(result) 值。

在您的外部文件中,您可以使用您正在使用的语法,以这种方式尝试查看 console.log 值。

这是查看更多信息的链接: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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