不要以诺言工作

时间:2017-06-01 04:01:53

标签: javascript

我试试这段代码:

function addNewCars(req, res) {
    let CarsList = req.body;
    carListParsing(carList)
        .then(function () {
        console.log('OK');
        res.status(200).send('OK');
    }).catch(function (err) {
        res.status(200).send(err);
    });
}

function carListParsing (data) {
    return new Promise(function (resolve, reject) {

        let newCar = {};
        newCar.name = data.car_name;
        validateCar(newCar).then(function (data) {
            console.log('validate result1: ', data); //this line doesn't show 
            //if I get validation result, I can use next function createCat()
            resolve(data);
        }).catch(function (err) {
            reject(err);
        });
    });
}

function validateCar(data) {
    db.cars.findAll({where: {name: data.name}}).then(function (org) {
        if (org.length < 1) {
            console.log('validate1: OK'); //work
            return data;
        } else {
            console.log('validate2: already exist'); //work
            return new Error('The ' + data.name + ' car is already exist.');
        }
    }).catch(function (err) {
        return err;
    });
}

我需要验证data =&gt;汽车名称,如果汽车不存在则创建新车并执行下一个逻辑,示例停车。如果找到汽车,那就进行功能停车。

1 个答案:

答案 0 :(得分:2)

避免carListParsing中的Promise constructor antipatternreturn validateCar的结果承诺!

function addNewCars(req, res) {
    // CarsList is a typo
    carListParsing(req.body)
    .then(function () {
        console.log('OK');
        res.status(200).send('OK');
    }, function (err) { // more appropriate than catch
        res.status(200).send(err);
    });
}

function carListParsing (data) {
    let newCar = {
        name: data.car_name
    };
    // don't call `new Promise`
    return validateCar(newCar).then(function (data) {
       console.log('validate result1: ', data); //this line doesn't show 
       // if I get validation result, I can use next function createCat()
       return data; // don't resolve
    });
}

function validateCar(data) {
    return db.cars.findAll({where: {name: data.name}}).then(function (org) {
//  ^^^^^^
        if (org.length < 1) {
            console.log('validate1: OK'); //work
            return data;
        } else {
            console.log('validate2: already exist'); //work
            throw new Error('The ' + data.name + ' car is already exist.');
//          ^^^^^ probably what you actually wanted
        }
    }) // don't ignore errors
}