为什么我得到的输出是undefined?

问题描述 投票:0回答:1

当我把userName和password参数传给setTimeout函数时,为什么我得到{ userName: undefined, password: undefined }作为最终输出?我从setTimeout函数中删除了它们,然后我得到了预期的输出。

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");
javascript ajax callback
1个回答
2
投票

回调函数采取 usernamepassword 参数,但你永远不会将它们作为参数传递。

你可以给 setTimeout这些变量将作为参数传递给回调。

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");

或者你也可以不输入参数,变量将被保存在闭包中。

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");

1
投票

你的 setTimeout 回调是影子的 userNamepassword 变量。您可以将它们从 setTimeout 回调或将它们作为参数添加到 setTimeout 这样叫。

setTimeout((userName, password) => {
    console.log("Iam inside the setTimeOut function");
    callback({
      userName: userName,
      password: password
    });
  }, 3000, userName, password)
© www.soinside.com 2019 - 2024. All rights reserved.