doubt about promises Javascript

1
function promise(){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            JSON.parse('ok'); //disparando excepción
        },100);
    });
}

promise()
    .then(null,function(error){
        alert('entrando a onRejected');
        alert(error);
        throw new Error('¿catch me atrapas?');
    })
    .catch(function(error){
        alert('entrando a catch');
        alert(error);
    });'

basically believed that when an error or exception occurred during the execution of the promise it was "captured" in the second parameter of the "then" method or in the "catch".

but in this case when an exception occurs within the "setTimeout" for some reason the execution of the promise is not completed, it is more than ever to execute "then" or "catch". if I delete the "setTimeout" error if it is captured in "then", it is as if the error was not propagated inside "setTimeout" to the promise and then to "onRejected".

How can I solve this problem?

    
asked by akira94 21.04.2017 в 13:31
source

2 answers

1

You have to use resolve(...) and reject(...) to indicate if there was an error in the promise. The then method contains the code you want to run when there were no problems with the promise.

function promise(){
    return new Promise(function(resolve,reject){
        setTimeout(function(){
            try{
                JSON.parse('ok'); //disparando excepción
                resolve("bueno"); // resolve() si no hay problemas
            }
            catch(ex){
                reject("malo");  // reject() si hay problemas
            }
        },100);
    });
}
promise()
    .then(function(resultado){
        alert('Sin problemas');
        alert(resultado);
        throw new Error('¿catch me atrapas?');
    }) 
    .catch(function(error){
        alert('entrando a catch');
        alert(error);
    });
    
answered by 21.04.2017 в 19:54
0

The promises do not handle exceptions by themselves, you must include a try catch in the body of the promise that when it detects an error is passed as a parameter to the callback reject. The then method is the action that must be executed when the promise has been fulfilled and the catch method is executed when an error occurred. The values returned by the then and catch methods are the same ones that you pass to the callbacks resolve and reject accordingly.

function promise(){
    return new Promise(function(resolve,reject){
      setTimeout(function(){
          try {
            let result = JSON.parse('ok') //disparando excepción
            resolve(result)
          } catch(e) {
            reject(e)                      
          }
      },100);
   })
}

promise()
    .then(function(result) {
      console.log(result)
     })
    .catch(function(error){
      console.log('Se produjo un error' + error)
    });
    
answered by 21.04.2017 в 19:37