What happens if you don't resolve or reject a promise?

前端 未结 5 2109
忘了有多久
忘了有多久 2020-12-04 15:24

I have a scenario where I am returning a promise. The promise is basically triggered by an ajax request.

On rejecting the promise it shows an error dialog that there

5条回答
  •  孤街浪徒
    2020-12-04 15:47

    As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:

    function makeRequest(ur,params) {
    
        return new Promise(function(resolve,reject) {
    
            fetch(url,params)
            .then((response) => {
    
                let status = response.status;
    
                if (status >= 200 && status < 300) {
                    response.json().then((data) => {
                        resolve(data);
                    })
                }
                else {
                    reject(response);
                }
            })
        });
    }
    
    makeRequest().then(function success(data) {
       //...
    }, function error(response) {
        if (response.status === 401) {
            redirectToLoginPage();
        }
        else {
            response.json().then((error) => {
                if (!error.message) {
                    error.message = constants.SERVER_ERROR;
                }
    
                //do sth. with error
            });
        } 
    });
    

    That means I would reject every bad response state and then handle this in your error handler of your makeRequest.

提交回复
热议问题