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

问题描述 投票:0回答:1

我手动将 json 对象连接到 Promise。第一个打印的下面的代码 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)

    })
javascript json promise node-fetch
1个回答
1
投票

稍微不同的方法可能涉及更新

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

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.