如何在javascript或节点中使其异步?

时间:2016-04-04 10:57:44

标签: javascript node.js asynchronous

var responseArr = new Array();
async.each(response, function (value, k) {
    if(isDateFlag)
    {
         var defaultValue = value.auction_id;
         grpArray.push(value.title);
         var postData = {
             parent_id : parent_id,
             defaultValue : defaultValue,
             isDateFlag : isDateFlag,
             search_text : search_text
         }
         getChildNotificationList(postData, function (childArrayData) {
            //Creating the response array

             responseArr.push({
                'notification_id' : childArrayData['notification_id'], 
                'notification_text' : childArrayData['notification_text']
             });
        });

     }
});

return responseArr;//Blank Array

我希望在从子数据查询中操作后返回最终的responseArr。它返回空白数组,因为它不等待查询响应。

那么它是如何异步的。感谢

1 个答案:

答案 0 :(得分:3)

我提到了http://justinklemm.com/node-js-async-tutorial/https://github.com/caolan/async

这是因为控件继续执行代码,因为javascript是同步的。要获得预期结果,请按以下方式修改代码:

var responseArr = new Array();
async.each(response, function (value, k) {
  if(isDateFlag){
    var defaultValue = value.auction_id;
    grpArray.push(value.title);
    var postData = {
      parent_id : parent_id,
      defaultValue : defaultValue,
      isDateFlag : isDateFlag,
      search_text : search_text
    }
    getChildNotificationList(postData, function (childArrayData) {
      //Creating the response array

      responseArr.push({
        'notification_id' : childArrayData['notification_id'], 
        'notification_text' : childArrayData['notification_text']
      });
      k();
    });
  } else {
    k();
  }
}, function (err) {
  if (err) {
    console.log(err);
  } else {
    return responseArr;
  }
});

上面的代码在功能块内。您可以通过调用函数来获得结果。

使用async.map包含答案

async.map(response, function (value, k) {
  if(isDateFlag){
    var defaultValue = value.auction_id;
    grpArray.push(value.title);
    var postData = {
      parent_id : parent_id,
      defaultValue : defaultValue,
      isDateFlag : isDateFlag,
      search_text : search_text
    }
    getChildNotificationList(postData, function (childArrayData) {

      k(null, {
        'notification_id' : childArrayData['notification_id'], 
        'notification_text' : childArrayData['notification_text']
      });
    });
  } else {
    k(null, {
      'notification_id' : '', 
      'notification_text' : ''
    });
  }
}, function(err, results){
  // results is now an array
  return results;
});