javascript - Node.js setTimeout 上下文问题

标签 javascript node.js ecmascript-6 settimeout

我正在模块内尝试以下操作( Node 8.9.0LTS):

   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 之外访问。

最佳答案

您不能在非异步函数中使用await。因此,最简单的解决方案是将函数更改为异步:

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

关于javascript - Node.js setTimeout 上下文问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47240377/

相关文章:

javascript - 在 Highcharts 中隐藏默认状态的行

node.js - (Sequelize+Postgres+Node JS) 从另一个表插入 FK(用户 ID)

javascript - 部署在heroku上的angularjs应用程序web.js结构

javascript - 尝试将事件从其组件之一传播到自定义 HTML 元素时抛出

javascript - 如何防止 react 重新渲染整个组件?

javascript - 如何检测使用 Leaflet-draw-toolbar 插件创建的弹出菜单中的 "delete"或 "edit"事件?

javascript - 从图像中获取像素颜色总是 0 0 0 0?

javascript - 如何在点击 div 时添加弹跳效果

javascript - 如何将 Node 环境变量传递给 React Native JS 代码

javascript - 将无状态组件拆分为更小的部分