我正在尝试在异步函数中获取一个异步函数,以返回创建和返回对象列表所需的数据。但是我似乎无法获得其余代码来等待异步功能完成。我尝试使用Promise,但它仍然没有等待异步功能。
我希望代码在'followed'子句中等待内部getUser
函数。
这是代码。
var count = 0;
var activities = [];
var getUsers = function(activity, callback){
var text_arr = activity.text.split("/");
get_user(res, text_arr[0], text_arr[0], function (user) {
if(user != null){
if (text_arr[2] == "created"){
activity = {
"id":activity.id,
"user_id":text_arr[0],
"user_name": user.user.name,
"event_name": text_arr[3],
"event_id": text_arr[4],
"event_img":(text_arr[5]) ? text_arr[5].split("$").join("/") : null,
"type": "CREATED_EVENT",
"date": activity.modified_ts
}
}
if (text_arr[2] == "commented"){
activity = {
"id":activity.id,
"user_id":text_arr[0],
"user_name": user.user.name,
"event_name": text_arr[3],
"event_id":text_arr[4],
"event_img": (text_arr[6]) ? text_arr[6].split("$").join("/") : null,
"comment": text_arr[5],
"type": "COMMENTED_EVENT",
"date": activity.created_ts
}
}
if (text_arr[2] == "followed"){
function f_promise() {
return new Promise(function (resolve, reject) {
get_user(res, text_arr[3], text_arr[3], function (following) {
resolve(following);
});
})
}
f_promise().then(following => {
activity = {
"id":activity.id,
"user_id":text_arr[0],
"user_name": user.user.name,
"followed_id": text_arr[3],
"followed_name": following.name,
"followed_img": (text_arr[5]) ? String(text_arr[6]).split("$").join("/") : null,
"type": "FOLLOWED_USER",
"date": activity.modified_ts
}
})
}
if (text_arr[2] == "liked"){
activity = {
"id":activity.id,
"user_id":text_arr[0],
"user_name": user.user.name,
"event_name": text_arr[3],
"event_id": text_arr[4],
"event_img": (text_arr[5]) ? text_arr[5].split("$").join("/") : null,
"type": "LIKED_EVENT",
"date": activity.modified_ts
}
}
if (text_arr[2] == "attending"){
activity = {
"id":activity.id,
"user_id":text_arr[0],
"user_name": user.user.name,
"event_name": text_arr[3],
"event_id": text_arr[4],
"name": text_arr[3],
"event_img":(text_arr[5]) ? text_arr[5].split("$").join("/") : null,
"type": "ATTENDED_EVENT",
"date": activity.modified_ts
}
}
activities.push(activity)
}
count++;
if(result.length == count){
callback(activities)
}
});
}
//start here
if(JSON.stringify(result) == "[]"){
var data = {"activities": []};
callback(data);
}else{
async.forEach(result, getUsers, function(activities) {
var data = {"activities":activities};
callback(data);
})
}