1

I am newbie in nodejs. Can some write me a sudo code that does the following?

Function1(); //returns an array which can be used in function2 and function3

Function2(); //returns an array which can be used in function3

Function3();

I want to run all three functions synchronously. So function2 has to wait for function1 to finish, then use the returned array in the function2. Then function3 waits for function2 to finish, then use the returned array in the function3 and so forth.

Tried something like this but then seems execute at the same time as well.

function main() {
    return Promise.resolve()
        .then (function(){
            function1()
        })
        .then (function(){
            function2()
        })
        .then (function(){
            function3()
        })
}
Nazmul Islam
  • 61
  • 3
  • 7
  • 2
    Javascript is fundamentally single-threaded. You don't want to execute them *synchronously,* but *in serial.* `const main = () => function1().then(function2).then(function3)` assuming they return promises. – CertainPerformance May 22 '18 at 02:01
  • 3
    Chaining all those `then()` doesn't do what you want because there is no `return` so they will all fire right away. Will depend on what you return in those functions also and how you get those arrays inside them – charlietfl May 22 '18 at 02:03
  • Have a look at this: https://stackoverflow.com/a/32718168/9816472 – Isaac May 22 '18 at 02:03

5 Answers5

2

This might be able to help you out:

function main() {
return Promise.resolve()
    .then (function(){
        return function1()
    })
    .then (function(results){
        // process your results
        return function2([pass arguments IF required])
    })
    .then (function(results){
        // process your results
        function3([pass arguments IF required])
    })
    .then (function (results) {
        return results
     })
    .catch(function(err) {
        console.log(err)
     })

}

So in short what you're missing out is returning the function value which is to be captured and used by next then.

0

Example where each of the functions returns a promise that resolves with the return of an array which gets passed to next function where each element in array gets multiplied by 10

Starting with [1,2,3] getting passed to function2 becomes [10,20,30] which gets passed to function3 and becomes [100,200,300]

function asynchFake(data){
  return new Promise((resolve)=>{
      setTimeout(()=> resolve(data),1000)
  })
}

function func1(){
  console.log('func1')
  return asynchFake([1,2,3])
}

function func2(func1Data){
  console.log('func2')
  return asynchFake(func1Data.map(v=>v*10));
}

function func3(func2Data){
  console.log('func3')
  return asynchFake(func2Data.map(v=>v*10))
}

function main() { 
    console.log('main')
    return func1().then(func2).then(func3)
}

main().then(res=>console.log('final results', res))
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • What if I don't wanna hard wait 1000ms? Let's say I have a database query in func1 and I want wait for query to finish before executing func2 – Nazmul Islam May 22 '18 at 02:48
  • The 1000ms is simply to create a fake asynchronous operation with a visual delay. Whatever db you use should have promise methods and you would use those promises instead to return from functions and resolve with the retrieved data – charlietfl May 22 '18 at 02:50
0

You could also try async/await to make the three functions run synchronously:

function function1(){
 return [1]
}

function function2(arr){
 return arr.concat([2])
}

function function3(arr){
 return arr.concat([3])
}

async function main(){
 let res = await function1(); // waits for function1 to complete before moving to the next line
 let res2 = await function2(res); // similarly waits for the completion of function2
 let res3 = await function3(res2); // similarly waits for the completion of function3
 console.log(res3)
 console.log("end of main")
}

main()
Parama Kar
  • 462
  • 3
  • 8
0

here are 2 ways you can achieve what you are looking for. It was a bit trickier as you were using two different functions, but I think I got what you are looking for.

  • Utilize a callback function
  • Utilize the node event emitter
Rubin bhandari
  • 1,873
  • 15
  • 20
0

There are 2 ways you can achieve what you are looking for.I think I got what you are looking for.

Utilize a callback function Utilize the node event emitter.

Rubin bhandari
  • 1,873
  • 15
  • 20