简体   繁体   中英

Why I am getting output as undefined?

Why I am getting { userName: undefined, password: undefined } as the final output when I pass userName and password parameters to setTimeout function? I removed them from setTimeout and see then I got the expected outputs

 console.log("Starting"); displayUser = (userName, password, callback) => { console.log("Iam inside the displayUser function") setTimeout((userName, password) => { console.log("Iam inside the setTimeOut function"); callback({ userName: userName, password: password }); }, 3000) } displayUser("Hasindu", "hasindu123", (user) => { console.log("Iam inside the call back function"); console.log(user); }); console.log("end");

The callback function takes username and password parameters, but you never pass them as arguments.

You can give additional arguments to setTimeout , and they'll be passed as arguments to the callback.

 console.log("Starting"); displayUser = (userName, password, callback) => { console.log("Iam inside the displayUser function") setTimeout((userName, password) => { console.log("Iam inside the setTimeOut function"); callback({ userName: userName, password: password }); }, 3000, userName, password) } displayUser("Hasindu", "hasindu123", (user) => { console.log("Iam inside the call back function"); console.log(user); }); console.log("end");

Or you could just leave out the parameters and the variables will be saved in the closure.

 console.log("Starting"); displayUser = (userName, password, callback) => { console.log("Iam inside the displayUser function") setTimeout(() => { console.log("Iam inside the setTimeOut function"); callback({ userName: userName, password: password }); }, 3000) } displayUser("Hasindu", "hasindu123", (user) => { console.log("Iam inside the call back function"); console.log(user); }); console.log("end");

Your setTimeout callback is shadowing the userName and password variables. You either remove them from the parameters of the setTimeout callback or add them as arguments to the setTimeout call like so:

setTimeout((userName, password) => {
    console.log("Iam inside the setTimeOut function");
    callback({
      userName: userName,
      password: password
    });
  }, 3000, userName, password)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM