Last active
September 30, 2017 15:06
-
-
Save pnmcosta/3a0eff421528944674f672b4e429976c to your computer and use it in GitHub Desktop.
Total.js - Using Promise to get schema objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
NEWSCHEMA('Form').make(function (schema) { | |
schema.define('contact', 'FormContact', true); | |
schema.define('deal', 'FormDeal', true); | |
schema.addWorkflow('submit', function (error, model, options, callback, controller) { | |
Promise.all([getDealById(options.deal_id), getContactById(options.contact_id)]) | |
.then(function (values) { | |
let valid = (values[0] && value[1]); // 0 = getDealById, 1 = getContactById | |
if (!valid) { | |
error.push('deal', 'not found.'); | |
return callback(model); | |
} | |
model.deal = values[0]; | |
model.contact = value[1]; | |
return callback(model); | |
}, function (err) { | |
// handle err, it was rejected by one or the other promise | |
error.push('email', err); | |
return callback(model); | |
}).catch(function (err) { | |
// handle err, unexpected error occured, e.g. unhandled exception | |
return callback(model); | |
}); | |
}); | |
function getContactById(id) { | |
return new Promise(function (resolve, reject) { | |
GETSCHEMA('Contact').get(id, function (err, data) { | |
if (err) reject(err); | |
else resolve(data); | |
}); | |
}) | |
}; | |
function getDealById(id) { | |
return new Promise(function (resolve, reject) { | |
GETSCHEMA('Deal').get(id, function (err, data) { | |
if (err) reject(err); | |
else resolve(data); | |
}); | |
}) | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment