嵌套异步但不等待,尽管有等待指示,程序仍运行

时间:2019-01-17 15:20:23

标签: javascript node.js express websocket async-await

在处理项目后端时遇到了这个错误。 WebSocket接收一个JSON对象,并进行过滤过程。在过滤过程中,我必须执行API调用以确定此JSON对象是否在用户声明的位置范围内。

我做了一个setTimeout,但是没有用。我尝试仅具有一个promise函数,但是没有起作用。剩下的就是尝试异步/等待。

app.post('/new-events', async (rq, rs) => {
  let events = rq.body.events || [];
  if (events.length === 0) {
    return rs.send(`No events found!`);
  }

  const nowTimestamp = (new Date()).getTime();
  const batchID = md5(nowTimestamp);

  for (let ei = 0; ei < events.length; ei++) {
    await (new Promise((rs, rj) => logNewEvents.insert({
      eventID: events[ei]._id,
      eventTitle: events[ei]._source.eventTitle,
      timestamp: nowTimestamp,
      rawEvent: JSON.stringify(events[ei]),
      batchID: `${batchID}_${events[ei]._id}`,
    }, e => e ? rj(false) : rs(true)))).catch(() => false);
  }

  wss.clients.forEach(client => {
    let response = new Result('update');
    if (client.readyState === ws.OPEN) {
      try {
         client.send(JSON.stringify(
          response.setData('events', events.filter(async(event) => {
            if (typeof client.options === 'undefined' || typeof client.filters === 'undefined') {
              return true;
            }
            let partLocations = client.filters.locations.map((l, i) => `locationCode[${i}]=${l._id}`).join('&');
            let partAction = `action=checkNews`;
            let partEventId = `_id=${event._id}`;
            let url = ApiUrl + [
              partLocations,
              partAction,
              partEventId
            ].join('&');
            let options = {
              uri: url,
              json: true,
              simple: true
            }

            console.log('should be awaiting');
            //performing request-promise-native
            //result.display displays true/false
            let passLocations = await request(options).then(result => result.display).catch(err => console.log(err));
            console.log(passLocations);
            console.log('after awaiting');


            let passQuery = (client.options.query === '' || event._source.eventTitle.toLowerCase().includes(client.options.query.toLowerCase()));
            let passCategories = client.filters.categories.length === 0 || client.filters.categories.map(c => c.toLowerCase()).includes(event._source.eventCategory.toLowerCase());
            let passImportance = ['Information', 'Warning', 'Critical'].filter(i => !!client.filters.importance[i]).length === 0 ||
              (client.filters.importance.information && event._source.eventImportance === 'Information') ||
              (client.filters.importance.warning && event._source.eventImportance === 'Warning') ||
              (client.filters.importance.critical && event._source.eventImportance === 'Critical');
            let passScope = ['Local', 'National', 'Global'].filter(i => !!client.filters.scope[i]).length === 0 ||
              (client.filters.scope.local && event._source.eventScope === 'Local') ||
              (client.filters.scope.national && event._source.eventScope === 'National') ||
              (client.filters.scope.global && event._source.eventScope === 'Global');

            logPushedEvents.insert({
              eventID: event._id,
              eventTitle: event._source.eventTitle,
              timestamp: (new Date()).getTime(),
              passQuery,
              passImportance,
              passScope,
              partLocations,
              passCategories,
              passFinal,
              client: client.user,
              options: client.options,
              filters: client.filters,
              rawEvent: JSON.stringify(event),
              batchID: `${batchID}_${event._id}`,
            });

            let passFinal = passQuery && passCategories && passImportance && passScope && passLocations;
            console.log('FINAL', passFinal);
            return passFinal;
          }))
            .setSuccess(true)
            .setMessage('Here you go!')
            .toJson()
        ));
      } catch (e) {
        console.log(e);
        console.log('error sending to client');
      }
    }
  });
  rs.send(`event dispatched!`);
});

预期: passLocation to display true/false然后 .setSuccess(true) .setMessage('here you go!') .toJson()

结果: .setSuccess(true) .setMessage('here you go!') .toJson() 然后 passLocation displays true/false

0 个答案:

没有答案