Promises Inside a For Loop
I have this code:
_getSupport()
.then((data) => {
_getSupport(data[0])
.then(() => _getSupport(data[1])
})
.catch(e => {
console.log(e);
});
_getSupport return a Promise.
My goal is to call again _getSupport on values returned the first time.
So I tought:
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Promise.all(a).then().catch(e => {
});
})
.catch( e => {console.log(e)})
But this does not work, the code always goes to the last catch.
UPDATE
The getSupport() is of this form
function _getSupport(param = {}) {
return new Promise((resolve, reject) => {
remoteClient.sendRequest(request, function (data) {
resolve(data);
});
});
}
javascript promise
add a comment |
I have this code:
_getSupport()
.then((data) => {
_getSupport(data[0])
.then(() => _getSupport(data[1])
})
.catch(e => {
console.log(e);
});
_getSupport return a Promise.
My goal is to call again _getSupport on values returned the first time.
So I tought:
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Promise.all(a).then().catch(e => {
});
})
.catch( e => {console.log(e)})
But this does not work, the code always goes to the last catch.
UPDATE
The getSupport() is of this form
function _getSupport(param = {}) {
return new Promise((resolve, reject) => {
remoteClient.sendRequest(request, function (data) {
resolve(data);
});
});
}
javascript promise
2
What is console logged in the last catch? It could be that_getSupport()return error from the start, or data is not an array, for example.
– Georgy
Nov 13 at 17:50
1
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54
add a comment |
I have this code:
_getSupport()
.then((data) => {
_getSupport(data[0])
.then(() => _getSupport(data[1])
})
.catch(e => {
console.log(e);
});
_getSupport return a Promise.
My goal is to call again _getSupport on values returned the first time.
So I tought:
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Promise.all(a).then().catch(e => {
});
})
.catch( e => {console.log(e)})
But this does not work, the code always goes to the last catch.
UPDATE
The getSupport() is of this form
function _getSupport(param = {}) {
return new Promise((resolve, reject) => {
remoteClient.sendRequest(request, function (data) {
resolve(data);
});
});
}
javascript promise
I have this code:
_getSupport()
.then((data) => {
_getSupport(data[0])
.then(() => _getSupport(data[1])
})
.catch(e => {
console.log(e);
});
_getSupport return a Promise.
My goal is to call again _getSupport on values returned the first time.
So I tought:
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Promise.all(a).then().catch(e => {
});
})
.catch( e => {console.log(e)})
But this does not work, the code always goes to the last catch.
UPDATE
The getSupport() is of this form
function _getSupport(param = {}) {
return new Promise((resolve, reject) => {
remoteClient.sendRequest(request, function (data) {
resolve(data);
});
});
}
javascript promise
javascript promise
edited Nov 15 at 17:32
asked Nov 13 at 17:46
giuseppe
5,27012650
5,27012650
2
What is console logged in the last catch? It could be that_getSupport()return error from the start, or data is not an array, for example.
– Georgy
Nov 13 at 17:50
1
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54
add a comment |
2
What is console logged in the last catch? It could be that_getSupport()return error from the start, or data is not an array, for example.
– Georgy
Nov 13 at 17:50
1
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54
2
2
What is console logged in the last catch? It could be that
_getSupport() return error from the start, or data is not an array, for example.– Georgy
Nov 13 at 17:50
What is console logged in the last catch? It could be that
_getSupport() return error from the start, or data is not an array, for example.– Georgy
Nov 13 at 17:50
1
1
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54
add a comment |
5 Answers
5
active
oldest
votes
Here lies the problem
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Since the data can have virtually anything in it; numbers, objects, strings anything, So when you set a[element] you are actually setting that particular property for the array.
a =
a['see_this?'] = 'does this even make sense?'
You get the point.
What you ought to do is
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
// or
a = data.map(element =>_getSupport(element));
and then use your Promise.all; of course if this is piece of function code you need to return it so others can .then() on it, so return Promise.all()
1
Ifelementis a number and_getSupport()returns an array of numbers like this[0,1,2,3]then usinga[0],a[1]etc should be just fine no?
– Akrion
Nov 13 at 17:58
1
@Akrion yes that would work perfectly fine. But the array must containnumbersand notstrings.
– Prasanna
Nov 13 at 18:00
1
@Akrion may be your_getSupportis throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your_getSupportfunction as well as the nature ofdata
– Prasanna
Nov 13 at 18:02
add a comment |
This answer is almost identical to other answers, just two cents: you can use .map instead of forEach and push.
let getPromiseObj = data => new Promise((resolve, reject) =>
setTimeout(
() => resolve(data || ['No', 'truthy', 'data']),
1000
)
)
getPromiseObj()
.then(res => Promise.all(res.map(getPromiseObj)))
.then(finalRes => console.log(finalRes))
.catch(e => console.error(e))
add a comment |
If you _getSupport is valid and does not throw an error to begin with you could also modify your code to something like this:
_getSupport()
.then(data => {
let a = ;
data.forEach(element => a[element] = _getSupport(element))
return Promise.all(a).then().catch(e => {})
})
.catch(e => console.log(e))
Where you also return the last Promise.all
add a comment |
Sometimes nested promises creates problems.
We need to accumulate promises into an array so that you can return them all.
That's why a.push() which will push the promises to the array.
The data in the next .then() function is an array of responses of each promise in the same order they are pushed.
Add console.log(data) to see on what values you are iterating on further.If data cannot be iterated then it might throw error.
Try to execute the "_getSupport()" function individually and see if you are getting any errors, if not then try my code it will work.
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
return Promise.all(a)
})
.then((data) => {
// If it returns an array of elements then this data will be
// [[0,1,2],[1,2,3] ...] based on the number of elements returned in
// first call
})
.catch( e => {console.log(e)})
add a comment |
Although all answers stimulated my brain, neither worked as expected.
The only solution I found stem from this answer :
_getSupport()
.then((data) => {
let sTypes = data.parameter.supported_types || ;
sTypes.reduce((p,value,currentIndex) => {
return p.then(() => _getSupport({ method: "get_supported_scale", sType: value }));
},Promise.resolve());
})
.catch(e => {
logger.error(e.stack);
});
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286793%2fpromises-inside-a-for-loop%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here lies the problem
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Since the data can have virtually anything in it; numbers, objects, strings anything, So when you set a[element] you are actually setting that particular property for the array.
a =
a['see_this?'] = 'does this even make sense?'
You get the point.
What you ought to do is
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
// or
a = data.map(element =>_getSupport(element));
and then use your Promise.all; of course if this is piece of function code you need to return it so others can .then() on it, so return Promise.all()
1
Ifelementis a number and_getSupport()returns an array of numbers like this[0,1,2,3]then usinga[0],a[1]etc should be just fine no?
– Akrion
Nov 13 at 17:58
1
@Akrion yes that would work perfectly fine. But the array must containnumbersand notstrings.
– Prasanna
Nov 13 at 18:00
1
@Akrion may be your_getSupportis throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your_getSupportfunction as well as the nature ofdata
– Prasanna
Nov 13 at 18:02
add a comment |
Here lies the problem
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Since the data can have virtually anything in it; numbers, objects, strings anything, So when you set a[element] you are actually setting that particular property for the array.
a =
a['see_this?'] = 'does this even make sense?'
You get the point.
What you ought to do is
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
// or
a = data.map(element =>_getSupport(element));
and then use your Promise.all; of course if this is piece of function code you need to return it so others can .then() on it, so return Promise.all()
1
Ifelementis a number and_getSupport()returns an array of numbers like this[0,1,2,3]then usinga[0],a[1]etc should be just fine no?
– Akrion
Nov 13 at 17:58
1
@Akrion yes that would work perfectly fine. But the array must containnumbersand notstrings.
– Prasanna
Nov 13 at 18:00
1
@Akrion may be your_getSupportis throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your_getSupportfunction as well as the nature ofdata
– Prasanna
Nov 13 at 18:02
add a comment |
Here lies the problem
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Since the data can have virtually anything in it; numbers, objects, strings anything, So when you set a[element] you are actually setting that particular property for the array.
a =
a['see_this?'] = 'does this even make sense?'
You get the point.
What you ought to do is
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
// or
a = data.map(element =>_getSupport(element));
and then use your Promise.all; of course if this is piece of function code you need to return it so others can .then() on it, so return Promise.all()
Here lies the problem
let a = ;
data.forEach(element => {
a[element] = _getSupport(element)
});
Since the data can have virtually anything in it; numbers, objects, strings anything, So when you set a[element] you are actually setting that particular property for the array.
a =
a['see_this?'] = 'does this even make sense?'
You get the point.
What you ought to do is
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
// or
a = data.map(element =>_getSupport(element));
and then use your Promise.all; of course if this is piece of function code you need to return it so others can .then() on it, so return Promise.all()
edited Nov 13 at 18:03
answered Nov 13 at 17:55
Prasanna
1,494616
1,494616
1
Ifelementis a number and_getSupport()returns an array of numbers like this[0,1,2,3]then usinga[0],a[1]etc should be just fine no?
– Akrion
Nov 13 at 17:58
1
@Akrion yes that would work perfectly fine. But the array must containnumbersand notstrings.
– Prasanna
Nov 13 at 18:00
1
@Akrion may be your_getSupportis throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your_getSupportfunction as well as the nature ofdata
– Prasanna
Nov 13 at 18:02
add a comment |
1
Ifelementis a number and_getSupport()returns an array of numbers like this[0,1,2,3]then usinga[0],a[1]etc should be just fine no?
– Akrion
Nov 13 at 17:58
1
@Akrion yes that would work perfectly fine. But the array must containnumbersand notstrings.
– Prasanna
Nov 13 at 18:00
1
@Akrion may be your_getSupportis throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your_getSupportfunction as well as the nature ofdata
– Prasanna
Nov 13 at 18:02
1
1
If
element is a number and _getSupport() returns an array of numbers like this [0,1,2,3] then using a[0], a[1] etc should be just fine no?– Akrion
Nov 13 at 17:58
If
element is a number and _getSupport() returns an array of numbers like this [0,1,2,3] then using a[0], a[1] etc should be just fine no?– Akrion
Nov 13 at 17:58
1
1
@Akrion yes that would work perfectly fine. But the array must contain
numbers and not strings.– Prasanna
Nov 13 at 18:00
@Akrion yes that would work perfectly fine. But the array must contain
numbers and not strings.– Prasanna
Nov 13 at 18:00
1
1
@Akrion may be your
_getSupport is throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your _getSupport function as well as the nature of data– Prasanna
Nov 13 at 18:02
@Akrion may be your
_getSupport is throwing an error in the first place and hence you are going to the last catch. It would be great if you edit your question with your _getSupport function as well as the nature of data– Prasanna
Nov 13 at 18:02
add a comment |
This answer is almost identical to other answers, just two cents: you can use .map instead of forEach and push.
let getPromiseObj = data => new Promise((resolve, reject) =>
setTimeout(
() => resolve(data || ['No', 'truthy', 'data']),
1000
)
)
getPromiseObj()
.then(res => Promise.all(res.map(getPromiseObj)))
.then(finalRes => console.log(finalRes))
.catch(e => console.error(e))
add a comment |
This answer is almost identical to other answers, just two cents: you can use .map instead of forEach and push.
let getPromiseObj = data => new Promise((resolve, reject) =>
setTimeout(
() => resolve(data || ['No', 'truthy', 'data']),
1000
)
)
getPromiseObj()
.then(res => Promise.all(res.map(getPromiseObj)))
.then(finalRes => console.log(finalRes))
.catch(e => console.error(e))
add a comment |
This answer is almost identical to other answers, just two cents: you can use .map instead of forEach and push.
let getPromiseObj = data => new Promise((resolve, reject) =>
setTimeout(
() => resolve(data || ['No', 'truthy', 'data']),
1000
)
)
getPromiseObj()
.then(res => Promise.all(res.map(getPromiseObj)))
.then(finalRes => console.log(finalRes))
.catch(e => console.error(e))
This answer is almost identical to other answers, just two cents: you can use .map instead of forEach and push.
let getPromiseObj = data => new Promise((resolve, reject) =>
setTimeout(
() => resolve(data || ['No', 'truthy', 'data']),
1000
)
)
getPromiseObj()
.then(res => Promise.all(res.map(getPromiseObj)))
.then(finalRes => console.log(finalRes))
.catch(e => console.error(e))
answered Nov 13 at 18:16
Georgy
1,155922
1,155922
add a comment |
add a comment |
If you _getSupport is valid and does not throw an error to begin with you could also modify your code to something like this:
_getSupport()
.then(data => {
let a = ;
data.forEach(element => a[element] = _getSupport(element))
return Promise.all(a).then().catch(e => {})
})
.catch(e => console.log(e))
Where you also return the last Promise.all
add a comment |
If you _getSupport is valid and does not throw an error to begin with you could also modify your code to something like this:
_getSupport()
.then(data => {
let a = ;
data.forEach(element => a[element] = _getSupport(element))
return Promise.all(a).then().catch(e => {})
})
.catch(e => console.log(e))
Where you also return the last Promise.all
add a comment |
If you _getSupport is valid and does not throw an error to begin with you could also modify your code to something like this:
_getSupport()
.then(data => {
let a = ;
data.forEach(element => a[element] = _getSupport(element))
return Promise.all(a).then().catch(e => {})
})
.catch(e => console.log(e))
Where you also return the last Promise.all
If you _getSupport is valid and does not throw an error to begin with you could also modify your code to something like this:
_getSupport()
.then(data => {
let a = ;
data.forEach(element => a[element] = _getSupport(element))
return Promise.all(a).then().catch(e => {})
})
.catch(e => console.log(e))
Where you also return the last Promise.all
answered Nov 13 at 17:54
Akrion
9,39211224
9,39211224
add a comment |
add a comment |
Sometimes nested promises creates problems.
We need to accumulate promises into an array so that you can return them all.
That's why a.push() which will push the promises to the array.
The data in the next .then() function is an array of responses of each promise in the same order they are pushed.
Add console.log(data) to see on what values you are iterating on further.If data cannot be iterated then it might throw error.
Try to execute the "_getSupport()" function individually and see if you are getting any errors, if not then try my code it will work.
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
return Promise.all(a)
})
.then((data) => {
// If it returns an array of elements then this data will be
// [[0,1,2],[1,2,3] ...] based on the number of elements returned in
// first call
})
.catch( e => {console.log(e)})
add a comment |
Sometimes nested promises creates problems.
We need to accumulate promises into an array so that you can return them all.
That's why a.push() which will push the promises to the array.
The data in the next .then() function is an array of responses of each promise in the same order they are pushed.
Add console.log(data) to see on what values you are iterating on further.If data cannot be iterated then it might throw error.
Try to execute the "_getSupport()" function individually and see if you are getting any errors, if not then try my code it will work.
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
return Promise.all(a)
})
.then((data) => {
// If it returns an array of elements then this data will be
// [[0,1,2],[1,2,3] ...] based on the number of elements returned in
// first call
})
.catch( e => {console.log(e)})
add a comment |
Sometimes nested promises creates problems.
We need to accumulate promises into an array so that you can return them all.
That's why a.push() which will push the promises to the array.
The data in the next .then() function is an array of responses of each promise in the same order they are pushed.
Add console.log(data) to see on what values you are iterating on further.If data cannot be iterated then it might throw error.
Try to execute the "_getSupport()" function individually and see if you are getting any errors, if not then try my code it will work.
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
return Promise.all(a)
})
.then((data) => {
// If it returns an array of elements then this data will be
// [[0,1,2],[1,2,3] ...] based on the number of elements returned in
// first call
})
.catch( e => {console.log(e)})
Sometimes nested promises creates problems.
We need to accumulate promises into an array so that you can return them all.
That's why a.push() which will push the promises to the array.
The data in the next .then() function is an array of responses of each promise in the same order they are pushed.
Add console.log(data) to see on what values you are iterating on further.If data cannot be iterated then it might throw error.
Try to execute the "_getSupport()" function individually and see if you are getting any errors, if not then try my code it will work.
_getSupport()
.then((data) => {
let a = ;
data.forEach(element => {
a.push(_getSupport(element))
});
return Promise.all(a)
})
.then((data) => {
// If it returns an array of elements then this data will be
// [[0,1,2],[1,2,3] ...] based on the number of elements returned in
// first call
})
.catch( e => {console.log(e)})
edited Nov 13 at 18:18
answered Nov 13 at 18:04
Saran Kumar Palivela
12
12
add a comment |
add a comment |
Although all answers stimulated my brain, neither worked as expected.
The only solution I found stem from this answer :
_getSupport()
.then((data) => {
let sTypes = data.parameter.supported_types || ;
sTypes.reduce((p,value,currentIndex) => {
return p.then(() => _getSupport({ method: "get_supported_scale", sType: value }));
},Promise.resolve());
})
.catch(e => {
logger.error(e.stack);
});
add a comment |
Although all answers stimulated my brain, neither worked as expected.
The only solution I found stem from this answer :
_getSupport()
.then((data) => {
let sTypes = data.parameter.supported_types || ;
sTypes.reduce((p,value,currentIndex) => {
return p.then(() => _getSupport({ method: "get_supported_scale", sType: value }));
},Promise.resolve());
})
.catch(e => {
logger.error(e.stack);
});
add a comment |
Although all answers stimulated my brain, neither worked as expected.
The only solution I found stem from this answer :
_getSupport()
.then((data) => {
let sTypes = data.parameter.supported_types || ;
sTypes.reduce((p,value,currentIndex) => {
return p.then(() => _getSupport({ method: "get_supported_scale", sType: value }));
},Promise.resolve());
})
.catch(e => {
logger.error(e.stack);
});
Although all answers stimulated my brain, neither worked as expected.
The only solution I found stem from this answer :
_getSupport()
.then((data) => {
let sTypes = data.parameter.supported_types || ;
sTypes.reduce((p,value,currentIndex) => {
return p.then(() => _getSupport({ method: "get_supported_scale", sType: value }));
},Promise.resolve());
})
.catch(e => {
logger.error(e.stack);
});
answered Nov 16 at 8:11
giuseppe
5,27012650
5,27012650
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53286793%2fpromises-inside-a-for-loop%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
What is console logged in the last catch? It could be that
_getSupport()return error from the start, or data is not an array, for example.– Georgy
Nov 13 at 17:50
1
I omitted the code, but data is always an array. The error e is empy.
– giuseppe
Nov 13 at 17:54