停止或违背承诺

时间:2017-03-07 09:28:38

标签: javascript node.js

如果图片有效,我正在尝试检查API。我正在使用promises,我希望如果检查API会让我失败,请停止执行de promise并调用函数。

继承我的代码。

我调用承诺的功能

 checkPhotos(options,formData, "front", res, false).then(function(response) {
    if(response!== 'error'){
        options.url = 'http://'+config.verifier_host+':'+config.verifier_port+config.verifier_endpoint_sc;
        readImage = fs.createReadStream("tmp/"+imgOne+".jpeg");
        formData = {
            uuid          : request.uuid,
            document_type : 1, //req.body.document_type
            analysis_type : 1,
            document_image: {
                value: readImage,
                options: {
                    filename: 'tmp/'+imgOne+'.jpeg',
                    contentType: null
                }
            }
        };

        console.log("2a Ejecución")
        return checkPhotos(options,formData, "back", res, false);
    }else {
        return;
    }
}).then(function(response) {
    if(response!== 'error'){
        options.url = 'http://'+config.verifier_host+':'+config.verifier_port+config.verifier_endpoint_sc;
        readImage = fs.createReadStream("tmp/"+nombreImagenBackimg2+".jpeg");
        formData = {
            uuid          : request.uuid,
            document_type : 1, //req.body.document_type
            analysis_type : 2,
            document_image: {
                value: readImage,
                options: {
                    filename: 'tmp/'+img2+'.jpeg',
                    contentType: null
                }
            }
        };

        console.log("3a Ejecución")
        return checkPhotos(options,formData, "back", res, false);
    }else {
        return;
    }
}).then(function(response) {
    if(response!== 'error'){
        readImage = fs.createReadStream("tmp/"+nombreImagenSelfieimg3+".jpeg");
        formData = {
            uuid        : request.uuid,
            selfie_image: {
                value: readImage,
                options: {
                    filename: 'tmp/'+img3+'.jpeg',
                    contentType: null
                }
            }
        };
        options.url = 'http://'+config.verifier_host+':'+config.verifier_port+config.verifier_endpoint_tc;
        console.log("4a y última ejecución")
        return checkPhotos(options, formData, null, res, true, request);
    }else {
        return;
    }
}).catch(function(err) {
    logger.error('PID ' + process.pid + ' Error response' + err.message);
    console.log("Catch -> "+ err.message);
});

我的职责承诺。

function checkPhotos (options, formData, positionPhoto, res, bandera, request) {
var promise = new Promise(function (resolve, reject) {

    var post_req = requests.post({headers: {Authorization : options.headers.authorization}, url:options.url, formData: formData}, function (err, httpResponse, body) {
        if (err) {
            logger.error(' PID ' + process.pid + err);
            return console.error('Error:', err);
        }

        if(!body){
            logger.error(' PID ' + process.pid +  formData.document_image.options.filename);
            return false; 
        }

        responseBody = JSON.parse(body);
        if(bandera){
            if(responseBody.success === 'error'){
                resolve(responseBody.success);
                return getData(null, res, responseBody);
            }else {
                resolve(formData);
                getData(null, res);
            }
        }else {
            if(responseBody.success === 'error'){
                logger.error(' PID ' + process.pid + responseBody);
                resolve(responseBody.success);
                return getData(null, res, responseBody);
            }else {
                resolve(formData);
                console.log("Success")
            }
        }
    });
});

return promise;

}

1 个答案:

答案 0 :(得分:0)

在错误时调用reject而不是resolve。这样,承诺链会立即被拒绝,并且不会对.then的任何后续调用运行。

如果要从.then调用中停止承诺链,可以返回Promise.reject(…)值或抛出错误。

示例:

const promise = checkPhotos(...);

promise
.then(askApi)
.then((response) => { throw response.body; })
.then(willNotBeExecuted)
.catch(thisWillbeExecutedAfterThrow);

function checkPhotos (options, formData, positionPhoto, res, bandera, request) {
  return (resolve, reject) => {
    // … make request
    if (!bandera) { reject(getData); }
  };
}