如何在javascript或节点中使其异步?
我想在从子数据查询中操作它之后返回最终的responseArr。它返回空数组,因为它不等待查询响应 那么它是如何异步的。谢谢我提到了 这是因为控件继续执行代码,因为javascript是同步的。要获得预期结果,请按以下方式修改代码:如何在javascript或节点中使其异步?,javascript,node.js,asynchronous,Javascript,Node.js,Asynchronous,我想在从子数据查询中操作它之后返回最终的responseArr。它返回空数组,因为它不等待查询响应 那么它是如何异步的。谢谢我提到了 这是因为控件继续执行代码,因为javascript是同步的。要获得预期结果,请按以下方式修改代码: var responseArr = new Array(); async.each(response, function (value, k) { if(isDateFlag) { var defaultValue = value.
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
上述代码位于功能块内。您可以通过调用函数来获得结果
包括使用async.map的答案:
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
而不是每个
。您需要调用k
。这里有一个简单的例子,你可以遵循@Bergi:为什么是async.map()??为什么要使用新阵列?@Thalaivar:因为您不需要响应器。使用map
@Thalaivar推送。。。谢谢你的帮助教程。它在回调中工作正常:)它将始终返回数组,直到循环开始。。。。在将所有子数据推送到主响应阵列之后,我需要发送一次。我认为您应该在问题中通过提供适当的代码示例来指定这一点。我已经回答了你发布的问题。您没有提到循环。:)代码以async.each循环开始。。对于技术人员来说,不必提及这一点。k!=回调
,您应该改用async.map
。另外,您的三个返回值都没有任何意义。如果未设置isDateFlag
,则不能忘记调用k
。
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;
});