I have this nested functions but it only called the first 2 functions and then skipped the others. Add it is too fast to redirect to another page. What I wanted to achieve is this and making sure that every instances finishes its job before proceeding to another instances:
Scenario:
First instance // first called
Sec instance // next called then
Third instance // next called then
Fourth instance // last called
May I know what did I do wrong?
This is what I did:
if (db_name != "" && contact != "" && email !="")
{
// createdb
session.rpc('/custom/createdb',
{
db_name: db_name,
}).then(function()
{
console.log("Database created successfully")
//initdb
session.rpc('/custom/initdb',
{
db_name: db_name,
}).then(function()
{
console.log("Database initialized successfully")
// IT SKIPS HERE
//installapps
session.rpc('/custom/installapps',
{
db_name: db_name,
}).then(function()
{
console.log("Apps installed successfully")
// AND HERE TOO
//createaccount
session.rpc('/custom/createaccount',
{
db_name : db_name,
contact_name: contact,
email_from: email,
}).then(function ()
{
console.log("User account created successfully")
});
});
});
})
}
If you write promise-based code that keeps nesting deeper and deeper, you're doing something wrong. Promises exist exactly to avoid this Christmas tree type of code.
Instead of nesting deeper and deeper, return the promises each of your RPC calls gives you. You also need to return the top-level promise from your worker function, so the calling code can wait until everything is finished:
function creacteAccount(db_name, contact, email) {
if (!(db_name > "" && contact > "" && email > "")) {
return Promise.reject("One of the parameters is empty");
}
return session.rpc('/custom/createdb', {db_name: db_name}) // return here
.then(function () {
console.log("Database created successfully");
return session.rpc('/custom/initdb', {db_name: db_name}); // and here
}).then(function () {
console.log("Database initialized successfully");
return session.rpc('/custom/installapps', {db_name: db_name}); // and here
}).then(function () {
console.log("Apps installed successfully");
return session.rpc('/custom/createaccount', { // and here
db_name : db_name,
contact_name: contact,
email_from: email
});
}).then(function () {
console.log("User account created successfully");
});
}
Do the redirect in the calling code's .then()
and the error handling in .catch()
:
creacteAccount("myDB", "contact", "email").then(function () {
// redirect...
}).catch(function (err) {
alert("Could not create account! (" + err + ")");
});