【问题标题】:Javascript/ReactJS execution of .then() is being performed too early [duplicate].then() 的 Javascript/ReactJS 执行执行得太早[重复]
【发布时间】:2020-04-09 22:49:23
【问题描述】:

我想在 POST-fetch 成功执行后重新渲染我的 React 组件。但是,当我 console.log 执行时间时,我注意到执行顺序已关闭。 我正在使用以下代码来获取时间:

function getTime(input) {
  var date = input ? new Date(input) : new Date();
  return {
      hours : date.getHours(),
      minutes : date.getMinutes(),
      seconds : date.getSeconds(),
      milliseconds : date.getMilliseconds()
  }
}

在我想在 fetch 之后重新渲染的主要组件中,我正在调用以下函数,该函数是从单独的 rest.js 文件中导入的:

fetchPushNewCourse(finalEvents).then(console.log("then 2 performed at", this.getTime()));

函数本身是这样的:

export async function fetchPushNewCourse(args){
  await fetch(`/calendar/post`, {
    method: "POST",
    body: JSON.stringify({ message: args }),
    headers: {
      "Content-Type": "application/json"
    }
  }).then(res => {
    console.log("then 1 performed at", getTime())
    return res.json();
  })
}

我希望“then 2”仅在执行 fetch 后被 console.logged,但它总是提前一秒左右执行。我似乎对 Promise 的工作原理有一个基本的误解。

【问题讨论】:

  • .then 接受一个 function 作为参数 - 检查你传递的内容 - 提示:undefined

标签: javascript reactjs promise fetch


【解决方案1】:

您没有通过 console.log('then 2') 传递 lambda,而是在声明的位置调用它。

很容易解决:

fetchPushNewCourse(finalEvents).then(() => console.log("then 2 performed at", this.getTime()));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    相关资源
    最近更新 更多