从承诺中获得回报并分配价值

时间:2020-08-15 11:56:17

标签: reactjs promise

我正在尝试从获取中返回值并将其分配给变量。数据正在返回,但是当我试图在变量中赋值时,我得到的是输出。

这是我的代码和输出

var getval=helper.GetRecord(objParam).then(response=>{return response});

输出 诺言 {} proto :承诺 [[PromiseStatus]]:“已实现” [[PromiseValue]]:对象 记录:“ 2020-08-15 02:18:55” 原始:对象

如何获取此记录数据的变量

1 个答案:

答案 0 :(得分:0)

您需要解决最终承诺。根据{{​​3}}

fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data));

以您的情况

helper.GetRecord(objParam)
  .then(response => response.json())
  .then(data => /*use data*/);

或使用await

将其分配给变量
const response = await helper.GetRecord(objParam);
const getval = await response.json();

如果GetRecord()返回了一个已解决的对象,而不是来自fetch()的完整响应,那么您仍然无法像您始终以getval一样尝试将其分配给.then()返回承诺。在这种情况下,您只需要处理回调中的响应即可。

helper.GetRecord(objParam)
  .then(response => /*use response*/);

或使用await

将其分配给变量
const getval = await helper.GetRecord(objParam);
相关问题