2017-06-22 125 views
0

我做一個簡單的睡眠承諾功能:JS等待拋出類型錯誤

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

再使用的await /異步在karmachai

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() 

的代碼可以UTIL第二的await工作。

'Unhandled promise rejection', TypeError{stack: '[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:53913:30 
[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14058:44 
[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14296:30 
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:14110:28 
[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51395:30 
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51406:17 
[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:50996:29 
http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:51009:31 
[email protected]://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59:50498:11', line: 53913, sourceURL: 'http://localhost:9876/base/index.js?312a09ec6fd4038632c2250d472217bc6ee69c59'} 

一個類型錯誤被拋出,但你可以看到,sleep函數從不拒絕Promise。還有一點是,第一個等待不會拋出異常。任何人都可以幫助我?

通天配置:

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

你怎麼知道這是'等待睡眠(...)'線後拋出的代碼? – Bergi

+0

....你是對的,業務代碼拋出這個異常,而不是睡覺。 – Leon

回答

0

我有同樣的問題。

向babel添加對異步等待的支持可以幫助我。

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

而這個預設添加到通天選項:

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

試試看吧。