1

My code is:-

function scammer(message) {
    return new Promise((resolve,reject)=>{
        if(condition){
            if (condition) {
                bot.KickMember(params).then((message)=>{
                    console.log("kicked");
                });
            } else {
                console.log("Not kicked");
            }
            resolve();
       }else{
          reject();
       }
   });
}

In the above code, function scammer works perfectly also the if-else statement but the then() does not work since I put it into a new promise, is there a way to execute then() without getting it out of the new promise.

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41
Smitk
  • 91
  • 1
  • 7
  • 1
    Your `then` function will be invoked when the promise you got from `bot.KickMember(params)` will be resolved. What's the problem with that? – sjahan Jul 12 '18 at 13:58
  • It's not clear what *is there a way to execute then() without getting it out of the new promise* means? – Liam Jul 12 '18 at 13:58
  • **I think** you just want to return the promise, `return bot.KickMember(params).then((message) => {` but that's a guess as I don't really understand your question – Liam Jul 12 '18 at 13:59
  • This is https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – Estus Flask Jul 12 '18 at 14:12
  • `resolve();` should be inside `bot.KickMember(params).then((message) => {`. otherwise promise will resolved before bot library do his work. – Hardik Shah Jul 12 '18 at 14:12
  • @HardikShahEdited the code – Smitk Jul 12 '18 at 14:24
  • Please edit correctly. Your code is currently messed up. Can not find anything promising. may be correct indentation. – Hardik Shah Jul 12 '18 at 14:28
  • Still, I would like to point out that your `resolve();` will resolve promises before bot work done. You should put `resolve()` inside `bot.KickMember(params).then((message)=>{` – Hardik Shah Jul 12 '18 at 14:31

2 Answers2

3

You don't need to create a promise, just return the one you got:

if (condition) {
    return bot.KickMember(params).then((message) => {
        console.log("kicked");
    });
} else {
    console.log("Not kicked");
    return Promise.reject(new Error("some reason"));
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Probably like this: resolve() should inside the bot promise.

function scammer(message) {
    return new Promise((resolve,reject)=>{
        if (condition) {
            bot.KickMember(params).then((message)=>{
                console.log("kicked");
                resolve();
            });
        } else {
            console.log("Not kicked");
            reject();
        }
    });
}

As per your code resolve() will execute before you land inside then of bot promise.

Correct me if I am wrong.

Hardik Shah
  • 4,042
  • 2
  • 20
  • 41