Reputation: 954
I am trying to make synchronous call to functions in my node js code.
I am calling my functions like this
set_authentication();
set_file();
function set_authentication(){
---
callback function
---
}
I want that my set_authentication() function should execute first completely and then set_file() should start execution but set_file() function start executing before the callback of set_authentication().
I have tried this using async also like
async.series(
[
// Here we need to call next so that async can execute the next function.
// if an error (first parameter is not null) is passed to next, it will directly go to the final callback
function (next) {
set_looker_authentication_token();
},
// runs this only if taskFirst finished without an error
function (next) {
set_view_measure_file();
}
],
function(error, result){
}
);
but it also doesn't work.
I tried promise also
set_authentication().then(set_file(),console.error);
function set_authentication(){
---
callback function
var myFirstPromise = new Promise((resolve, reject) => {
setTimeout(function(){
resolve("Success!");
}, 250);
});
---
}
here I am getting this error:- Cannot read property 'then' of undefined.
I am new to node and js.
Upvotes: 1
Views: 8835
Reputation: 982
use async.auto
like this:
async.auto(
{
first: function (cb, results) {
var status=true;
cb(null, status)
},
second: ['first', function (results, cb) {
var status = results.first;
console.log("result of first function",status)
}],
},
function (err, allResult) {
console.log("result of executing all function",allResult)
}
);
Upvotes: 0
Reputation: 3200
You need to return Promise, because you call .then
method of a returned promise:
set_authentication().then(set_file);
function set_authentication() {
return new Promise(resolve => { // <------ This is a thing
setTimeout(function(){
console.log('set_authentication() called');
resolve("Success!");
}, 250);
});
}
function set_file(param) {
console.log('set_file called');
console.log(
'received from set_authentication():', param);
}
Upvotes: 3
Reputation: 2047
If set_authentication
is async func, you need to pass set_file
as callback to set_authentication
function.
You may also consider to use promises as you wrote, but you need to implement it before you start chaining.
Upvotes: 1