【问题标题】:js await throw TypeErrorjs 等待抛出 TypeError
【发布时间】:2017-06-22 16:31:56
【问题描述】:

我做了一个简单的睡眠承诺函数:

let sleep = function(time) {
  return new Promise(function (resolve) {
    setTimeout(function () {
        resolve();
    }, time);
  })
}

然后在 karmachai 中使用 await/async

var test = async function() {

  // works  
  await sleep(DELAY)

  let secondItem = vm.$el.querySelectorAll('.el-table__row')[1]
  let secondItemTds = secondItem.querySelectorAll('td')

  // throw exception
  await sleep(DELAY)
  secondItemTds[0].click()
  expect(rowClickCnt).equal(0)

  // if I CATCH the above exception, here throw exception again
  await sleep(DELAY)
  secondItem[5].click()
  expect(rowClickCnt).equal(1)
}

test()

代码可以在第二次等待后运行。

'Unhandled promise rejection', TypeError{stack: '_callee$@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:53913:30
tryCatch@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14058:44
invoke@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14296:30
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14110:28
step@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51395:30
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51406:17
run@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:50996:29
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51009:31
flush@http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:50498:11', line: 53913, sourceURL: 'http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59'}

一个 TypeError 被抛出,但正如你所见,sleep 函数永远不会拒绝Promise。还有一点就是第一次await不会抛出异常。谁能帮帮我?

Babel 配置:

{
  "presets": [
    ["env", { "modules": false }],
    "stage-2"
  ],
  "plugins": ["transform-runtime"],
  "comments": false,
  "env": {
    "test": {
      "presets": ["env", "stage-2"],
      "plugins": [ "istanbul" ]
    }
  }
}

【问题讨论】:

  • 你怎么知道是await sleep(…) 后面的代码在抛出?
  • ....你是对的,业务代码抛出这个异常,而不是休眠。

标签: javascript asynchronous


【解决方案1】:

我也遇到了同样的问题。

为 babel 添加对 async await 的支持对我有帮助。

npm install --save-dev babel-preset-es2017

并将这个预设添加到 babel 选项中:

"presets": [ <your presets> , "es2017"]

请尝试一下。

【讨论】:

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