【发布时间】:2017-06-22 16:31:56
【问题描述】:
我做了一个简单的睡眠承诺函数:
let sleep = function(time) {
return new Promise(function (resolve) {
setTimeout(function () {
resolve();
}, time);
})
}
然后在 karma 和 chai 中使用 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(…)后面的代码在抛出? -
....你是对的,业务代码抛出这个异常,而不是休眠。