在 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
});
但我得到 undefined
作为 result
,获取该值的正确方法是什么?
当您尝试 return 承诺在另一个文件中使用它时,您必须使用以下语法:
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)
});
}
这就是您创建承诺以在您想要的地方使用的方式,如果它有错误,它将发送到 catch 块,否则您应该看到 console.log(result) 值。
并且在您的外部文件中,您可以使用您正在使用的语法,以这种方式尝试查看 console.log 值。
这里有一个link可以查看更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
testFunction
不是 return 承诺,所以你不能使用 then
或 catch
和 returns undefined
因为嗯,这不是 returning 任何东西。
尝试 return 类似下面示例的承诺,但是我不确定 dispatch 参数应该做什么,所以我删除了它,希望这会有所帮助:
export const testFunction = () => {
return new Promise((resolve, reject) => {
otherFunction().then(( response ) => {
//do something...
resolve(response);
}).catch(( error ) => {
//do something...
reject(error);
});
});
}
我是 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
});
但我得到 undefined
作为 result
,获取该值的正确方法是什么?
当您尝试 return 承诺在另一个文件中使用它时,您必须使用以下语法:
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)
});
}
这就是您创建承诺以在您想要的地方使用的方式,如果它有错误,它将发送到 catch 块,否则您应该看到 console.log(result) 值。
并且在您的外部文件中,您可以使用您正在使用的语法,以这种方式尝试查看 console.log 值。
这里有一个link可以查看更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
testFunction
不是 return 承诺,所以你不能使用 then
或 catch
和 returns undefined
因为嗯,这不是 returning 任何东西。
尝试 return 类似下面示例的承诺,但是我不确定 dispatch 参数应该做什么,所以我删除了它,希望这会有所帮助:
export const testFunction = () => {
return new Promise((resolve, reject) => {
otherFunction().then(( response ) => {
//do something...
resolve(response);
}).catch(( error ) => {
//do something...
reject(error);
});
});
}