First of all you need to actually return promises from your functions and provide functions (not results of function calls) to .then() callbacks.
var env = [
'dev',
'prd',
'tst',
]
env.forEach(currentEnv => {
Promise.resolve()
.then(() => firstFunction(currentEnv))
.then(() => secondFunction(currentEnv))
});
function firstFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('firstFunction ' + env)
resolve();
}, 2000);
}).catch((error) => {
console.log('something went wrong' + env + "error: " + error);
});
};
function secondFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('secondFunction ' + env)
resolve();
}, 1000);
}).catch(() => {
console.log('something went wrong')
});
}
Doing that is enough to make your calls to be in order "all firstFunction() calls then all secondFunction() calls".
But if you need to make next environment to wait for the completion of work of the current one, you may use async iterator construction. It's relatively new feature, so I assume that you're using at least Node 10.x.
var env = [
'dev',
'prd',
'tst',
];
function firstFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('firstFunction ' + env)
resolve();
}, 2000);
}).catch((error) => {
console.log('something went wrong' + env + "error: " + error);
});
};
function secondFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('secondFunction ' + env)
resolve();
}, 1000);
}).catch(() => {
console.log('something went wrong')
});
}
async function *getAsyncIterator(env) {
for (const currentEnv of env) {
await firstFunction(currentEnv);
await secondFunction(currentEnv);
yield currentEnv;
}
}
async function doStuff() {
for await (const currentEnv of getAsyncIterator(env)) {
console.log(`Complete work on ${currentEnv}`)
}
}
doStuff();
UPDATE:
And finally, the third option is applying a recursive algorithm, in case when some older node version must be supported.
var env = [
'dev',
'prd',
'tst',
];
function firstFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('firstFunction ' + env)
resolve();
}, 2000);
}).catch((error) => {
console.log('something went wrong' + env + "error: " + error);
});
};
function secondFunction(env) {
return new Promise(resolve => {
setTimeout(() => {
console.log('secondFunction ' + env)
resolve();
}, 1000);
}).catch(() => {
console.log('something went wrong')
});
}
function doStuff(env = []) {
if (env.length === 0) return;
const [ currentEnv, ...restEnvs ] = env;
return Promise.resolve()
.then(() => firstFunction(currentEnv))
.then(() => secondFunction(currentEnv))
.then(() => doStuff(restEnvs));
}
doStuff(env).then(() => console.log('job done'));
renameConfigFile,runBuildScriptin your code. The outcome looks exactly what you expect.renameConfigFilesupposed to befirstFunctionandrunBuildScript-secondFunction?