-1

I am trying to call the one function after the other. I am working with discord.js and this is my code:


function1(function2)

async function function1(callback) {
    var guild = client.guilds.cache.get(config.Server);

    let channels = guild.channels;
    
    for (const channel of channels.cache.values()) 
    {
        //stuff...
    }
    callback();
}
async function function2(){
    //stuff
}

My problem here is that the callback isn't working... Any help?

Panos
  • 11
  • 5
  • Put the callback after the `console.log('2sec')` into the `setTimeout`…!? Only what you pass to `setTimeout` waits for 2 seconds, not everything outside it. – deceze Aug 16 '21 at 09:53
  • You're calling the callback before `setTimeout` completes – slebetman Aug 16 '21 at 09:53
  • This is an example... In my code it's not a timeout. It's a process that takes a few seconds. And i can't put the callback in the block because it's a foreach function and that would call it several times. – Panos Aug 16 '21 at 09:56
  • Then you'll need to supply an actual realistic code sample that we can actually help you with. – deceze Aug 16 '21 at 09:57
  • So what exactly is `build.channels.cache.forEach`? It completes asynchronously? Then it probably also has some way to chain another call after it. But without details about the relevant library, we can only speculate. – deceze Aug 16 '21 at 10:05
  • I just included the actual code in my question... I hope i am more clear now... – Panos Aug 16 '21 at 10:06
  • Oh guild.channels.cache.forEach fetches all the channels in a guild. And i need it to be async for the code inside the block. But i think i can make it synchronised as well by making some changes. Even making it sync how can i make it call the one after the other? – Panos Aug 16 '21 at 10:09
  • May you please even mention the word *discord* or do we have to guess that? – deceze Aug 16 '21 at 10:10
  • You probably want something like a `Promise.all(...map(...))` instead of a `forEach`… https://stackoverflow.com/a/59461196/476 – deceze Aug 16 '21 at 10:12
  • Well sorry about not mentioning that i am working with discord.js... I've changes the way i fetch the channels... I hope now i am more clear. – Panos Aug 16 '21 at 11:21

1 Answers1

1

You can do it like this:

test(test2);

function test(callback){
    setTimeout(() => {
        console.log('2sec')
        callback();
    }, 2000)
    
}

function test2(){
    console.log('success')
}

Danial
  • 1,603
  • 2
  • 15
  • 24
  • As i said in the comment this was an example. The actual process in not a setTimeout and if i called the function inside the foreach block, it would call it several times. Thanks for answering though. – Panos Aug 16 '21 at 10:05