How to handle successive axios.get in Promise?
I have data like this:
const resultData = {};
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
and I'd like to make a GET request to each urls.
If the request succeeds, I wanna add the response to resultData
.
If not, do nothing and do not raise any errors.
resultData
will be like this:
resultData = {
'foo': { ...responseOfFoo },
'bar': { ...responseOfBar },
};
I wrote a code like below, but this does not realize what I want to do.
axios raise a error when the request fails with 404, and in addition, async/await does not seem to be working correctly.
import _ from 'lodash';
return new Promise((resolve, reject) => {
const resultData = {};
_.forEach(data, async (url, key) => {
const res = await axios.get(url).catch(null);
resultData[key] = res.data;
});
resolve(resultData);
});
What is wrong with this?
I also tried using axios.all
or Promise.all
, but could not handle each error of the request properly.
javascript promise axios
add a comment |
I have data like this:
const resultData = {};
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
and I'd like to make a GET request to each urls.
If the request succeeds, I wanna add the response to resultData
.
If not, do nothing and do not raise any errors.
resultData
will be like this:
resultData = {
'foo': { ...responseOfFoo },
'bar': { ...responseOfBar },
};
I wrote a code like below, but this does not realize what I want to do.
axios raise a error when the request fails with 404, and in addition, async/await does not seem to be working correctly.
import _ from 'lodash';
return new Promise((resolve, reject) => {
const resultData = {};
_.forEach(data, async (url, key) => {
const res = await axios.get(url).catch(null);
resultData[key] = res.data;
});
resolve(resultData);
});
What is wrong with this?
I also tried using axios.all
or Promise.all
, but could not handle each error of the request properly.
javascript promise axios
add a comment |
I have data like this:
const resultData = {};
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
and I'd like to make a GET request to each urls.
If the request succeeds, I wanna add the response to resultData
.
If not, do nothing and do not raise any errors.
resultData
will be like this:
resultData = {
'foo': { ...responseOfFoo },
'bar': { ...responseOfBar },
};
I wrote a code like below, but this does not realize what I want to do.
axios raise a error when the request fails with 404, and in addition, async/await does not seem to be working correctly.
import _ from 'lodash';
return new Promise((resolve, reject) => {
const resultData = {};
_.forEach(data, async (url, key) => {
const res = await axios.get(url).catch(null);
resultData[key] = res.data;
});
resolve(resultData);
});
What is wrong with this?
I also tried using axios.all
or Promise.all
, but could not handle each error of the request properly.
javascript promise axios
I have data like this:
const resultData = {};
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
and I'd like to make a GET request to each urls.
If the request succeeds, I wanna add the response to resultData
.
If not, do nothing and do not raise any errors.
resultData
will be like this:
resultData = {
'foo': { ...responseOfFoo },
'bar': { ...responseOfBar },
};
I wrote a code like below, but this does not realize what I want to do.
axios raise a error when the request fails with 404, and in addition, async/await does not seem to be working correctly.
import _ from 'lodash';
return new Promise((resolve, reject) => {
const resultData = {};
_.forEach(data, async (url, key) => {
const res = await axios.get(url).catch(null);
resultData[key] = res.data;
});
resolve(resultData);
});
What is wrong with this?
I also tried using axios.all
or Promise.all
, but could not handle each error of the request properly.
javascript promise axios
javascript promise axios
edited Nov 21 '18 at 9:08
Taichi
asked Nov 21 '18 at 8:50
TaichiTaichi
19610
19610
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.
Something like:
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
Promise
.all(
Object
.entries( data )
.map(({ name, url }) => axios
.get( url )
.catch( error => {
throw new Error( `Failed GET request for ${ name }` );
// Individual GET request error handler.
})
)
)
.then( results => {
})
.catch( error => {
// error on the Promise.all level, or whatever an individual error handler throws.
// So if the url of foo rejects, it will get thrown again by the catch clause after .get()
// So the error would be 'Failed GET request for foo'.
});
If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()
If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.
The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to theresultData
.
– Taichi
Nov 21 '18 at 9:10
Don't re-throw incatch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append.catch(null)
to each axios.get, but I'll try it.
– Taichi
Nov 21 '18 at 9:47
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%2f53408272%2fhow-to-handle-successive-axios-get-in-promise%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.
Something like:
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
Promise
.all(
Object
.entries( data )
.map(({ name, url }) => axios
.get( url )
.catch( error => {
throw new Error( `Failed GET request for ${ name }` );
// Individual GET request error handler.
})
)
)
.then( results => {
})
.catch( error => {
// error on the Promise.all level, or whatever an individual error handler throws.
// So if the url of foo rejects, it will get thrown again by the catch clause after .get()
// So the error would be 'Failed GET request for foo'.
});
If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()
If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.
The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to theresultData
.
– Taichi
Nov 21 '18 at 9:10
Don't re-throw incatch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append.catch(null)
to each axios.get, but I'll try it.
– Taichi
Nov 21 '18 at 9:47
add a comment |
Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.
Something like:
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
Promise
.all(
Object
.entries( data )
.map(({ name, url }) => axios
.get( url )
.catch( error => {
throw new Error( `Failed GET request for ${ name }` );
// Individual GET request error handler.
})
)
)
.then( results => {
})
.catch( error => {
// error on the Promise.all level, or whatever an individual error handler throws.
// So if the url of foo rejects, it will get thrown again by the catch clause after .get()
// So the error would be 'Failed GET request for foo'.
});
If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()
If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.
The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to theresultData
.
– Taichi
Nov 21 '18 at 9:10
Don't re-throw incatch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append.catch(null)
to each axios.get, but I'll try it.
– Taichi
Nov 21 '18 at 9:47
add a comment |
Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.
Something like:
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
Promise
.all(
Object
.entries( data )
.map(({ name, url }) => axios
.get( url )
.catch( error => {
throw new Error( `Failed GET request for ${ name }` );
// Individual GET request error handler.
})
)
)
.then( results => {
})
.catch( error => {
// error on the Promise.all level, or whatever an individual error handler throws.
// So if the url of foo rejects, it will get thrown again by the catch clause after .get()
// So the error would be 'Failed GET request for foo'.
});
If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()
If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.
The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.
Use Promise.all and append the .catch() error handler to the end of each GET request, so that if they throw an error, it gets caught Before the Promise.all groups the results.
Something like:
const data = {
'foo': 'https://valid/url/1',
'bar': 'https://valid/url/2',
'baz': 'https://INVALID/url/3',
};
Promise
.all(
Object
.entries( data )
.map(({ name, url }) => axios
.get( url )
.catch( error => {
throw new Error( `Failed GET request for ${ name }` );
// Individual GET request error handler.
})
)
)
.then( results => {
})
.catch( error => {
// error on the Promise.all level, or whatever an individual error handler throws.
// So if the url of foo rejects, it will get thrown again by the catch clause after .get()
// So the error would be 'Failed GET request for foo'.
});
If you throw an error inside the catch clause of the GET requests, the error will bubble up to the catch clause after the Promise.all()
If you return a value from inside the catch clause, that will be the result of the get request then in the results array, so you can still use the two requests that did succeed.
The following example will just return an object describing the problem if one of the 'get requests' fails and will check the results together for validity.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
If you need to be able to handle a GET request error individually and still trigger the .then() clause for the rest of the urls, you can't really batch all the requests together to begin with.
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
Promise
.all([
Promise.resolve( 'ok1' ).then( result => ({ "status": "ok", "value": result })),
Promise.resolve( 'ok2' ).then( result => ({ "status": "ok", "value": result })),
Promise.reject( 'nok3' ).catch( error => ({ "status": "nok", "value": error }))
])
.then( results => {
results.forEach(( result, index ) => {
if ( result.status === 'ok' ) console.log( `promise ${ index } resolved correctly: ${ result.value }`);
else console.log( `promise ${ index } rejected with error: ${ result.value }` );
});
})
.catch( error => console.error( error ));
edited Nov 21 '18 at 9:47
answered Nov 21 '18 at 9:00
ShillyShilly
5,4131616
5,4131616
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to theresultData
.
– Taichi
Nov 21 '18 at 9:10
Don't re-throw incatch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append.catch(null)
to each axios.get, but I'll try it.
– Taichi
Nov 21 '18 at 9:47
add a comment |
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to theresultData
.
– Taichi
Nov 21 '18 at 9:10
Don't re-throw incatch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append.catch(null)
to each axios.get, but I'll try it.
– Taichi
Nov 21 '18 at 9:47
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if
'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to the resultData
.– Taichi
Nov 21 '18 at 9:10
Thank you, but how can I ignore the error if any of the url returns 404? Like in my question, even if
'baz': 'https://INVALID/url/3'
throws not found, the rest data is inserted to the resultData
.– Taichi
Nov 21 '18 at 9:10
Don't re-throw in
catch
– Balázs Édes
Nov 21 '18 at 9:12
Don't re-throw in
catch
– Balázs Édes
Nov 21 '18 at 9:12
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
You can replace the catch clause where I rethrow an error with any error handling you desire, like checking the status codes and such. The point I wanted to make is that, you can catch the individual GET request errors there. And if you want to 'bubble up' the error to the catch clause after the Promise.all, like for further error handling on a different level, you can just throw a new error inside the catch of the GET requests so it will bubble up through the promise chain.
– Shilly
Nov 21 '18 at 9:35
Ok, it seemed not to work even if I append
.catch(null)
to each axios.get, but I'll try it.– Taichi
Nov 21 '18 at 9:47
Ok, it seemed not to work even if I append
.catch(null)
to each axios.get, but I'll try it.– Taichi
Nov 21 '18 at 9:47
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.
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%2f53408272%2fhow-to-handle-successive-axios-get-in-promise%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