0

I manually concat a json object to a promise. The code below on the first print, cosole.log(new_response) gets me this, which is what I want

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

However the second print, cosole.log(data_json_array) gets me the json object without the key-value, a: '123'

I don't know why is that. I would like the json object to include the key-value a: '123' For example:

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

Thanks in advance.

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)

    })
Sun Tianyi
  • 93
  • 1
  • 6

1 Answers1

1

A slightly different approach could involve updating someFunction to handle the json() and handle merging the data with the provided url. This can help avoid nested 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));

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91
  • Thank you! I will see how I can integrate into my code, will let you know the result. Much appreciated. – Sun Tianyi Jul 17 '21 at 00:18
  • Great. The point is that you can do more in the someFunction as it creates the promises and has the parameters. You could always do additional object assign in the consumer to merge additional data but this way it you don’t have to deal with json() at the consumer level. – Alexander Staroselsky Jul 17 '21 at 00:21
  • Coming back here to say thanks! I've successfully integrated into my code! @Alexander Staroselsky – Sun Tianyi Jul 19 '21 at 00:41