【问题标题】:How to use await with "$.get"?如何将等待与“$.get”一起使用?
【发布时间】:2020-08-13 05:40:12
【问题描述】:

每当我尝试运行此功能时:

async function jget(url){
    await $.get(url, html => {
        return html
    })
}

我收到这样的错误:

(node:13924) UnhandledPromiseRejectionWarning: #<Object>

我该如何解决这个问题?

【问题讨论】:

  • @epascarello 这个问题似乎是 TypeScript 特有的。
  • 我已经看到了这个问题,我尝试了解决方案,但它们对我不起作用。
  • 那里的代码可以很好地与 JavaScript 配合使用
  • 为什么在 node.js 中使用 jquery?

标签: javascript jquery node.js asynchronous async-await


【解决方案1】:

您应该将 "$.get(url, handlerFunction)" 放入一个 Promise 中,因为 await 期望 Promise 返回,因此您可以编写如下代码,而不是您的代码。

async function jget(url){
    // Note: Below variable will hold the value of the resolved promise
    let response = await fetchingData(url);
}

function fetchingData(url) {
    return new Promise((resolve, reject) => {
      $.get(url, html => {
        resolve(html)
    })
})
}

【讨论】:

  • 我不得不向 jget 添加“返回响应”,但它运行良好!非常感谢!
  • 避免Promise constructor antipatternjQuery.get 已经返回了一个承诺!你的方法是忽略错误。
猜你喜欢
  • 2019-06-26
  • 2020-01-17
  • 1970-01-01
  • 2017-03-01
相关资源
最近更新 更多