处理Js承诺拒绝

时间:2017-04-14 07:15:50

标签: javascript es6-promise

如何处理超出承诺的错误(例如,"新错误"以下)?

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Off Screen Canvas</title>
<script>
    function createOffscreenCanvas() {
        var offScreenCanvas = document.createElement('canvas');
        offScreenCanvas.width = '1360';
        offScreenCanvas.height = '400';
        var context = offScreenCanvas.getContext("2d");
        var W=200;
        var H=200;
        particleCount = 200;
        particles = []; //this is an array which will hold our particles Object/Class
        function Particle() {
            this.x = Math.random() * W;
            this.y = Math.random() * H;
            this.direction ={"x": -1 + Math.random()*2, "y": -1 + Math.random()*2};
            this.vx = 2 * Math.random() + 4 ;
            this.vy = 2 * Math.random() + 4;
            this.radius = .9 * Math.random() + 1;
            this.move = function(){
                this.x += this.vx * this.direction.x;
                this.y += this.vy * this.direction.y;
            };
            this.changeDirection = function(axis){
                this.direction[axis] *= -1;
            };
            this.draw = function() {
                context.beginPath();
                context.fillStyle = "#0097a7";
                context.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
                context.fill();
            };
            this.boundaryCheck = function(){
                if(this.x >= W){
                    this.x = W;
                    this.changeDirection("x");
                }
                else if(this.x <= 0){
                    this.x = 0;
                    this.changeDirection("x");
                }
                if(this.y >= H){
                    this.y = H;
                    this.changeDirection("y");
                }
                else if(this.y <= 0){
                    this.y = 0;
                    this.changeDirection("y");
                }
            };
        }
        function createParticles(){
            for (var i = particleCount-1; i >= 0; i--) {
                p = new Particle();
                particles.push(p);
            }
        }// end createParticles
        function drawParticles(){
            for (var i = particleCount-1; i >= 0; i--){
                p = particles[i];
                p.draw();
            }
        } //end drawParticles

        function updateParticles(){
            for(var i = particles.length - 1; i >=0; i--){
                p = particles[i];
                p.move();
                p.boundaryCheck();

            }
        }//end updateParticle
        createParticles();
        var part=drawParticles();
        context.fillStyle=part;
        context.fillRect(W-190, H-190, W, H);
        context.fill();
        return offScreenCanvas;
    }
    function copyToOnScreen(offScreenCanvas) {
        var onScreenContext=document.getElementById('onScreen').getContext('2d');
        var offScreenContext = offScreenCanvas.getContext('2d');
        var image=offScreenContext.getImageData(10,10,200,200);
        onScreenContext.putImageData(image,offScreenCanvas.width/2,offScreenCanvas.height/4);
    }

    function main() {
        copyToOnScreen(createOffscreenCanvas());
    }
</script>
<style>
    canvas {
        border: 1px solid red;
    }
</style>
</head>
<body onload="main()"> 
<canvas id="onScreen" width="1360" height="400"></canvas>
 </body>
</html>

5 个答案:

答案 0 :(得分:6)

如果您不确定函数是否会同步抛出(或返回值),可以使用.then()调用它。这将包装它,以便无论如何生成结果都将得到一致处理:

&#13;
&#13;
function testError() {
  throw new Error("new error") // how to handle this?
  var p123 = new Promise(function(resolve, reject) {
    resolve(123)
  });
  return p123
};

Promise.resolve()
  .then(testError)
  .catch(err => {
    console.error(err);
    return err; 
  })
  .then(ok => {
    console.log(ok.message)
  });
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于错误并不涉及异步代码,因此常规try { testError().catch(err => { return err; // code doesn't come here }) .then(ok => { console.log(ok) }); } catch(e) { // } 应该可以正常运行:

async-await

请注意,当try-catch模式最终成为解析promise的本机方式时,try { var ok = await testError(); console.log(ok) } catch(e) { console.log('e:' +e); } 也将成为处理错误的本机方式:

then-catch

可以轻松验证,这个正确处理同步和异步错误,并且比@echo off & setlocal EnableDelayedExpansion set j=0 for /f "delims=""" %%i in (config.ini) do ( set /a j+=1 set con!j!=%%i call set a=%%con!j!%% echo !a! (echo !a!|findstr "^#">nul 2>nul && ( rem mkdir !a! ) || ( echo +) rem for /f "tokens=2" %%k in(config.ini) do echo %%k ) ) pause 更清晰。

答案 2 :(得分:0)

由于错误是在promise之外引发的,因此无法使用promise catch语句捕获它。

您可以使用try / catch来捕获错误。

function testError() {
    throw new Error("new error") // how to handle this?
    var p123 = new Promise(function(resolve, reject) {
         resolve(123)
    });
    return p123
};

try {
  testError().then(ok => {
    console.log(ok)
  });
} catch (err) {
  console.log(err.message);
}

答案 3 :(得分:0)

如果可以,请重写testError功能

function testError () {
  return new Promise(function (resolve, reject) {
     throw new Error('new error')
     resolve(123)
  })
}

testError().then(ok => console.log(ok),
                 err => console.error(err.message))

  1. 运行一次以查看它在console.error
  2. 中抛出错误
  3. 注释throw行以查看承诺成功解决

答案 4 :(得分:0)

你重写它,因为调用者检查异常和拒绝是一种反模式:

function testError() {
  return Promise.resolve().then(() => {
    throw new Error("new error"); // rejects returned promise
    return new Promise(function(resolve) {
      resolve(123);
    });
  });
}

testError().catch(err => console.log("Caught " + err));

这是async函数隐含的;他们总是回应一个承诺:

async function testError() {
  throw new Error("new error"); // rejects implicit promise
  return await new Promise(function(resolve) {
    resolve(123);
  });
}

testError().catch(err => console.log("Caught " + err));