繁体   English   中英

Concat json to promise:如何从promise pending 中获取json 对象中的附加键值对

[英]Concat json to promise: How to get additional key value pair in json object from promise pending

我手动将一个 json 对象连接到一个承诺。 下面的第一次打印代码 cosole.log(new_response) 得到了我这个,这就是我想要的

Promise { <pending>, a: '123' }

然而,第二个打印 cosole.log(data_json_array) 得到了没有键值的 json 对象,a: '123'

我不知道这是为什么。 我希望 json 对象包含键值 a: '123' 例如:

{ 
  key1: "1",
  key2: "2",
  a: "123
}

提前致谢。

Promise.all(somefunction(parameter)).then(function (responses) {

        return Promise.all(responses.map(function (response) {

            new_json = {a: "123"}
            var new_response = Object.assign(response.json(), new_json)
            console.log(new_response)
            return new_response

      }.then(function (data) {

        console.log(data)

    })

一种稍微不同的方法可能涉及更新someFunction以处理 json() 并处理将数据与提供的 url 合并。 这可以帮助避免嵌套的Promise.all

 function someFunction(parameter) { // create array of promises return parameter.urls.map((url) => fetch(url) // parse JSON .then((res) => res.json()) // Merge data with url property .then((data) => ({ ...data, url })) ); } Promise.all( someFunction({ urls: [ "https://jsonplaceholder.typicode.com/todos/1", "https://jsonplaceholder.typicode.com/todos/2", ], }) ).then((data) => console.log(data));

希望这有帮助!

暂无
暂无

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

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