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)
})
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!