0
function doCall(a){
    return new Promise ((f) => {
        f(a * 2);
    });
}

function test () {
    let i = 10;
    doCall(i).then((a) => {
        i = a;
    });
    console.log(i);
}

I'm pretty sure the i=20, just don't want to be stupid because it seems obvious. Thanks

aaa
  • 1
  • 1
  • 1
    I assume the typo on `Promis` is just a mistake when you posted it.... – epascarello May 15 '23 at 18:44
  • 3
    You probably want to run it and verify it is not 20. :) – epascarello May 15 '23 at 18:45
  • @epascarello I don't think await is needed here? There is no async/await. Also the Promise returns `a*20` if I'm not mistaken. The `f` is confusing, usually this would be called `resolve`. @aman I think this code will log `10` since the function inside Promise is only executed on "next tick". Even though theoretically you don't have any asynchronous events here and it *could* all run through in order, it does not. The anonymous arrow function inside your Promise gets "scheduled" for the next event loop, and only gets executed **after** your `console.log(i)` – Codebling May 15 '23 at 19:07
  • @Codebling It is async... it logs 10, not 20. It does not matter that the code inside the promise is synchronous, it is still going to be async. `function test () { let i = 10; doCall(i).then((a) => { i = a; console.log('inside then', i); }); console.log('after then', i); }` run that.... – epascarello May 15 '23 at 19:08
  • @epascarello I agree it logs 10 and that it is asynchronous. `async` and `await` are keywords, though, so your statement was ambiguous and could have meant: 1) there is no point using asynchronous code here, or 2) OP should use `await` keyword. I agree with the former statement and disagree with the latter. – Codebling May 15 '23 at 19:12
  • Well it ain't synchronous or it would be 10.... – epascarello May 15 '23 at 19:17
  • 1
    @Codebling "*the function inside Promise is only executed on "next tick"*" - [no it's not](https://stackoverflow.com/q/42118900/1048572). What is executed asynchronously is the `.then(…)` callback. – Bergi May 15 '23 at 19:40

0 Answers0