Rejecting a promise when using a selection

I'm a little confused about how to use the selection correctly. It seems to be solvable even when I return the error status. Is the code below (wrapping a selection in another promise) correct?

function a(url, config) { if (!config) config = {}; config = Object.assign(config, { headers: { 'content-type': 'application/json;charset=utf-8' } }) return new Promise( function(resolve, reject) { fetch(url, config).then( function(res) { if (res.status == 200 && res.ok) { console.log("Promise resolved") resolve(res); return; } console.log("Promise rejected") reject(res); }, function(rej) { console.log("promise rejected") reject(rej); } ) } ) } function b() { a('/test').then( function(res) { console.log('success'); console.log(res) }, function(rej) { console.log('Rejected'); console.log(rej) } ) } b(); 
(The above code should work fine in chrome through the console ... just copy / paste)
+5
source share
1 answer

If you want to refuse the success callback, you need to do it explicitly, or reject a rejected promise, for example. return Promise.reject('error occurred'); or by throwing.

In addition, you should not use the Promise constructor in your case, since fetch already returns a promise object:

 function a(url, config) { if (!config) config = {}; config = Object.assign(config, { headers: { 'content-type': 'application/json;charset=utf-8' } }); return fetch(url, config).then( function(res) { if (res.status == 200 && res.ok) { console.log("Promise resolved") return res.json(); } console.log("Promise rejected"); throw 'promise rejected'; }, function(rej) { console.log("promise rejected"); throw 'promise rejected'; } ); } 
+2
source

Source: https://habr.com/ru/post/1237495/


All Articles