2017-11-11 140 views
0

我想一個模塊(節點8.9.0LTS)內的以下內容:的Node.js的setTimeout方面的問題

const someResponse = await ajaxService.post('/data/search', params) 
    const ms = 2000; 

    const intervalID = setInterval(function(){ 
    if(Object.keys(personDataResponse).length === 0){ 
     let url = `/api?searchRequestId=1111` 
     response = await ajaxService.get(url) 
    } 
    }, ms); 

    setTimeout(function() { 
     clearInterval(intervalID); 
    }, ms * 5); 

但我收到以下:

/path/to/project/project/api/router.js:27 
      response = await ajaxService.get(url) 
             ^^^^^^^^^^^ 

SyntaxError: Unexpected identifier 
    at createScript (vm.js:80:10) 
    at Object.runInThisContext (vm.js:139:10) 
    at Module._compile (module.js:599:28) 
    at Object.Module._extensions..js (module.js:646:10) 
    at Module.load (module.js:554:32) 
    at tryModuleLoad (module.js:497:12) 
    at Function.Module._load (module.js:489:3) 
    at Module.require (module.js:579:17) 
    at require (internal/module.js:11:18) 
    at Object.<anonymous> (/path/to/project/project/app.js:16:8) 

有什麼建議? ajaxService.get()在setTimeout之外是可訪問的。

+2

'setInterval'的意圖是在這裏?看起來你每兩秒運行一次請求五次,然後停止它。 – JLRishe

回答

3

您不能在非異步函數中使用await。因此最簡單的解決辦法是給你的函數更改爲async

       // v--- here 
const intervalID = setInterval(async function() { 
    if(Object.keys(personDataResponse).length === 0){ 
    let url = `/api?searchRequestId=1111` 
    response = await ajaxService.get(url) 
    } 
}, ms); 
0

您是否嘗試過在這裏使用單引號?

let url = '/api?searchRequestId=1111'

你不會需要回剔反正如果你沒有任何串聯變量的字符串。