Javascript 在 JSON 对象中转换承诺

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44331581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:27:57  来源:igfitidea点击:

Convert promise in JSON object

javascriptangularjsjsonangular-promise

提问by VitezKoja

I have a problem converting the promise returned by the service to the controller. What I want is to create an array of JSON objects from the data contained in promise. Here is what I receive in the controller: Data received at controller

我在将服务返回的承诺转换为控制器时遇到问题。我想要的是从 promise 中包含的数据创建一个 JSON 对象数组。这是我在控制器中收到的内容: 控制器接收到的数据

Here is the line that is used for printing that data:

这是用于打印该数据的行:

console.log("controller unmatched: ", unmatched.getData(sFilter));

Here "unmatched" is the service, and getData() is its function.

这里“unmatched”是服务,getData() 是它的函数。

Thanks!

谢谢!

回答by Lennholm

A Promise represents a value that will be available some time in the future, or never. This means its eventual value can't be returned by your unmatched.getData()function.

Promise 代表一个值,该值将在未来某个时间可用,或者永远不会可用。这意味着您的unmatched.getData()函数无法返回其最终值。

What you need to do is to make unmatched.getData()return the actual promise and then you take action when that promise resolves:

您需要做的是unmatched.getData()返回实际的承诺,然后在该承诺解决时采取行动:

unmatched.getData(sFilter).then(function(result) {
  console.log("controller unmatched: ", result);
});

回答by Vladimir Zdenek

I believe what you really want to do is save a value the promise resolves to, not the promise itself.

我相信你真正想做的是保存承诺解决的价值,而不是承诺本身。

unmatched.getData(sFilter).then(response => {
    const json = JSON.stringify(response);
});

This is due to the nature of promises - they are asynchronous.

这是由于 Promise 的性质——它们是异步的。

The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Promise 对象表示异步操作的最终完成(或失败)及其结果值。

Source: Promises on MDN

资料来源:MDN 上的承诺

回答by Hitmands

Promises work async:

Promise 异步工作:

unmatched
  .getData(sFilter)

  // wait for its resolution
  .then(data => console.log(JSON.stringify(data))
;

回答by Harikrishnan S

if you want to get the JSON objects from the promise, I think you can use the below line of code

如果您想从承诺中获取 JSON 对象,我认为您可以使用以下代码行

response.json()

响应.json()