gpt4 book ai didi

javascript - 为什么我的 Promise 没有同步运行?

转载 作者:行者123 更新时间:2023-11-28 11:01:44 25 4
gpt4 key购买 nike

环顾四周,找不到答案。我正在尝试运行一个 Promise,一旦所有 facebook api 页面都被迭代并保存到数组中,它就会执行执行语句。

我知道这个函数很丑陋,但我正在尝试看看我能用 Promise 走多远。

function pageThroughLikes(facebookPostArray) {
var testArray = []
return new Promise(function (fulfill, reject) {
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject) {
if ('paging' in innerObject.likes) {
if ('next' in innerObject.likes.paging) {
nextPage = innerObject.likes.paging.next;
currentPostId = innerObject.id;
currentDataLength = innerObject.likes.data.length;
i = 0;
do{
$.get(nextPage, function(nextLikePageData) {
likeData = {};
likeData.id = currentPostId;
likeData.likes = {};
likeData.likes.data = nextLikePageData.data
likeData.likes.paging = nextLikePageData.paging
console.log(likeData)
testArray.push(likeData);
facebookPostArray.push(testArray);
console.log('pushed to postArray')
})
i += 1;
} while (currentDataLength != 0 && i > 10)
}
}
}
})
});
fulfill();
console.log('paged through likes')
})
}

目前,一旦该函数完成,我想运行一个“测试”函数,将生成的数组转换为 CSV 格式并下载 CSV 文件。

这是我的测试函数:

function test() {
var convertedPostCSV = convertArrayOfObjectsToCSV(postArray);
downloadCSV(convertedPostCSV);
}

这是我的函数运行顺序:

$(document).ready(function() {
getPostLikes().then(function() {
pageThroughLikes(postArray).then(function() {
test();
});
});
});

我遇到的问题是,我的“test()”函数在新的点赞页面的数据添加到我的“facebookPostArray”之前或在 pageThroughLikes 函数结束之前运行。

希望有人能给我一些建议/指出我正确的方向。

编辑

好的,我已经按照 @Winter Soldier 的建议重新格式化了我的代码,但我仍然收到 processData 函数的未捕获错误。

这是我的代码:

function pageThroughLikes(facebookPostArray) {
console.log('paging through likes')
var testArray = []
var promiseList = [];
return new Promise(function (fulfill, reject) {
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject) {
if ('paging' in innerObject.likes) {
if ('next' in innerObject.likes.paging) {
nextPage = innerObject.likes.paging.next;
currentPostId = innerObject.id;
currentDataLength = innerObject.likes.data.length;
i = 0;
do{
promiseList.push(
$.ajax({url : nextPage
}))
i += 1;
} while (currentDataLength != 0 && i > 10)
}
}
}
});
return promiseList;
console.log('paged through likes')
})

processData = function(nextLikePageData){
likeData = {};
likeData.id = currentPostId;
likeData.likes = {};
likeData.likes.data = nextLikePageData.data
likeData.likes.paging = nextLikePageData.paging
console.log(likeData)
testArray.push(likeData);
facebookPostArray.push(testArray);
console.log('pushed to postArray')
return likeData;
}

$(document).ready(function() {
getPostLikes().then(function() {
$.when.apply(pageThroughLikes(postArray), this).done(function() {

var testArray = []
$.each(arguments, function(k, v){
var dt = processData(v[0]);
testArray.push(dt);
facebookPostArray.push(dt);
});
console.log(testArray)
test(testArray); // OR
test(facebookPostArray);
});
});
});

function test(postArray) {
var convertedPostCSV = convertArrayOfObjectsToCSV(postArray);
downloadCSV(convertedPostCSV);
}

编辑2.0

这是我的完整代码,尽管很丑陋。仅供引用。认为问题可能出在我隐藏在代码其余部分中的某个地方,因此可能值得向您展示完整的内容......

var facebookKey = config.FACEBOOK_KEY;

// ASSIGN QUERY TO VARIABLE

var likePage = getQueryVariable("likePage");
var sinceDate = getQueryVariable("sinceDate");
var likeArray = [];
var postArray = [];


function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
alert("Query Variable " + variable + " not found");
}

console.log("Page Search: " + likePage);
console.log("Since: " + sinceDate)

// FIND DATA FOR FACEBOOK PAGE POSTS SINCE CHOSEN DATE

$(document).ready(function() {
getPostLikes().then(function() {
$.when.apply(pageThroughLikes(postArray), this).done(function() {
var testArray = []
$.each(arguments, function(k, v){
var dt = processData(v[0]);
testArray.push(dt);
facebookPostArray.push(dt);
});
console.log(testArray)
test(testArray); // OR
test(facebookPostArray);
});
});
});

function test(postArray) {
var convertedPostCSV = convertArrayOfObjectsToCSV(postArray);
downloadCSV(convertedPostCSV);
}

function getPostLikes(response) {
return new Promise(function (fulfill, reject) {
$.get("https://graph.facebook.com/v2.8/"+ likePage + "?fields=access_token,posts.since(" + sinceDate + "){likes{id}}&access_token=" + facebookKey, function (facebookData) {

var likePageId = facebookData.id;
var testPostArray = [];
if ('posts' in facebookData) {
var nextPage = facebookData.posts.paging.next;
var check = 0;

postArray.push(facebookData.posts.data);

var currentDataLength = " "
var i = 0
if ('paging' in facebookData.posts) {
console.log("new page available");
do {
$.ajax({
async: false,
type: "GET",
url: nextPage,
success: function(nextPageData) {
console.log("New Page Accessed: " + nextPage)
i++;
console.log("Page Number: " + i)
testPostArray.push(nextPageData.data);
if ('paging' in nextPageData) {
nextPage = nextPageData.paging.next;
console.log("next page assigned");
}
currentDataLength = nextPageData.data.length;
console.log(currentDataLength);
}
});
console.log("DATA LENGTH: " + currentDataLength);
} while (currentDataLength > 0);
testPostArray.forEach(function(element) {
console.log(element)
postArray.push(element);
fulfill();
});
}
} else {
console.log('Error: No facebook posts since this date!')
reject();
}
console.log(postArray)
});
})
};
console.log("Downloading...")


function pageThroughLikes(facebookPostArray) {
console.log('paging through likes')
var testArray = []
var promiseList = [];
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject) {
if ('paging' in innerObject.likes) {
if ('next' in innerObject.likes.paging) {
nextPage = innerObject.likes.paging.next;
currentPostId = innerObject.id;
currentDataLength = innerObject.likes.data.length;
i = 0;
do{
promiseList.push(
$.ajax({url : nextPage
}))
i += 1;
} while (currentDataLength != 0 && i > 10)
}
}
}
})
});
console.log('paged through likes')
return promiseList;
}

processData = function(nextLikePageData){
likeData = {};
likeData.id = currentPostId;
likeData.likes = {};
likeData.likes.data = nextLikePageData.data
likeData.likes.paging = nextLikePageData.paging
console.log(likeData)
testArray.push(likeData);
facebookPostArray.push(testArray);
console.log('pushed to postArray')
return likeData;
}


// AUTO DOWNLOAD CSV FILE

function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV(postArray);

if (csv == null) return;

filename = args.filename || 'export.csv';

if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);

link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}
// CONVERT FACEBOOK POSTS OBJECTS TO CSV FORMAT

function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;

data = args || null;
if (data == null || !data.length) {
return null;
}

columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';

keys = Object.keys(data[0]);

result = '';
result += "user_id" + columnDelimiter + " post_id" + columnDelimiter + " page_id";
result += lineDelimiter;

data.forEach(function(item) {
item.forEach(function(post) {
if ('likes' in post) {
var likeArray = post.likes
likeArray.data.forEach(function(like) {
result += like.id + columnDelimiter + post.id.split('_').reverse() + lineDelimiter;
});
} else {
result += columnDelimiter + post.id.split('_').reverse() + lineDelimiter;
};
});
});
console.log('converted to CSV')
return result;
}

编辑3.0

功能几乎已修复,唯一的问题是它不循环。不过运行一次就完美了!

function pageThroughLikes(facebookPostArray) {
console.log('paging through likes')
var testArray = []
var promiseList = [];
// return new Promise(function (fulfill, reject) {
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject) {
if ('paging' in innerObject.likes) {
if ('next' in innerObject.likes.paging) {
nextPage = innerObject.likes.paging.next;
currentPostId = innerObject.id;
currentDataLength = innerObject.likes.data.length;
i = 0;
do{
promiseList.push(
$.ajax({url : nextPage
}).then(function(data, b, promise){
data.id = currentPostId;
if ('paging' in data) {
if ('next' in data.paging) {
nextPage = data.paging.next;
}
}
console.log(nextPage)
return promise;
}))
i += 1;
console.log(i)
} while (currentDataLength != 0 && i > 10)
}
}
}
})
});
console.log('paged through likes')
return promiseList;
}

编辑4.0

这是我当前的代码...

几乎一切终于正常了,成功地从深夜的谷歌搜索中获得了一堆信息。

var facebookKey = config.FACEBOOK_KEY;

// ASSIGN QUERY TO VARIABLE
var likePage = getQueryVariable("likePage");
var sinceDate = getQueryVariable("sinceDate");
var likeArray = [];
var postArray = [];

function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (pair[0] == variable) {
return pair[1];
}
}
alert("Query Variable " + variable + " not found");
}
console.log("Page Search: " + likePage);
console.log("Since: " + sinceDate)

// FIND DATA FOR DOJOAPP FACEBOOK PAGE POSTS SINCE CHOSEN DATE

$(document).ready(function() {
getPostLikes().then(function() {
// console.log(postArray);
pageThroughLikes(postArray, test)
});
});

function test(postArray) {
var convertedPostCSV = convertArrayOfObjectsToCSV(postArray);
downloadCSV(convertedPostCSV);
}

function getPostLikes(response) {
return new Promise(function (fulfill, reject) {
$.get("https://graph.facebook.com/v2.8/"+ likePage + "?fields=access_token,posts.since(" + sinceDate + "){likes{id}}&access_token=" + facebookKey, function (facebookData) {
var likePageId = facebookData.id;
var testPostArray = [];
if ('posts' in facebookData) {
var nextPage = facebookData.posts.paging.next;
var check = 0;
postArray.push(facebookData.posts.data);
var currentDataLength = " "
var i = 0
if ('paging' in facebookData.posts) {
console.log("new page available");
do {
$.ajax({
async: false,
type: "GET",
url: nextPage,
success: function(nextPageData) {
console.log("New Post Page Accessed: " + nextPage)
i++;
console.log("Paging Through Posts: " + i)
testPostArray.push(nextPageData.data);
if ('paging' in nextPageData) {
nextPage = nextPageData.paging.next;
console.log("next page assigned: " + nextPage);
}
currentDataLength = nextPageData.data.length;
console.log(currentDataLength);
}
});
console.log("DATA LENGTH: " + currentDataLength);
} while (currentDataLength > 0);
testPostArray.forEach(function(element) {
// console.log(element)
postArray.push(element);
fulfill();
});
}
} else {
console.log('Error: No facebook posts since this date!')
reject();
}
// console.log(postArray)
});
})
};
console.log("Downloading...")


function pageThroughLikes(facebookPostArray, callback) {
console.log('paging through likes')
var testArray = []
var promiseList = [];
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject && 'paging' in innerObject.likes && 'next' in innerObject.likes.paging) {
var nextPage = innerObject.likes.paging.next;
console.log('new likes page assigned: ' + nextPage);
var currentPostId = innerObject.id;
var noMorePages = false;
var i = 0;
do{
$.ajax({
url: nextPage,
success: function(nextLikePageData) {
createLikeObject(nextLikePageData, currentPostId, checkForPagesOfLikes, nextLikePageData, noMorePages)
if ('paging' in nextLikePageData && 'next' in nextLikePageData.paging) {
nextPage = nextLikePageData.paging.next;
}
}
})
i += 1
console.log(i)
} while (noMorePages = false);
}
})
});
console.log('paged through likes')
callback();
}

function createLikeObject(likeData, postId, callback, args, fail) {
likeArrayFormat = [];
likeObject = {};
likeObject.likes = {};
likeObject.id = postId;
likeObject.likes.data = []
likeData.data.forEach(function(like) {
likeObject.likes.data.push(like);
});
likeArrayFormat.push(likeObject);
postArray.push(likeArrayFormat);
console.log('pushed new like data to postArray')
callback(args, fail)
}

function pushToArray(item, array, callback) {
array.push(item);
callback()
}

function checkForPagesOfLikes(data, noMorePages) {
if ('paging' in data && 'next' in data.paging) {
return true;
console.log('NEW PAGE FOUND')
}
else {
noMorePages = true;
console.log('NO MORE PAGES OF LIKES FOR CURRENT OBJECT')
}
}

// AUTO DOWNLOAD CSV FILE
function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV(postArray);
if (csv == null) return;
filename = 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}

// CONVERT FACEBOOK POSTS OBJECTS TO CSV FORMAT

function convertArrayOfObjectsToCSV(args, callback) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
// console.log(args)
data = args || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
result = '';
result += "user_id" + columnDelimiter + " post_id" + columnDelimiter + " page_id";
result += lineDelimiter;
// console.log(args)
args.forEach(function(object) {
// console.log(object)
// console.log(object.length)
if (object.length != 0) {
object.forEach(function(item) {
if ('likes' in item && 'data' in item.likes) {
var postId = item.id;
item.likes.data.forEach(function(likeId) {
if ('id' in likeId) {
// console.log(likeId)
var likeArray = likeId;
// console.log(likeArray)
result += likeArray.id + columnDelimiter + postId.split('_').reverse() + lineDelimiter;
} else {
result += columnDelimiter + postId.split('_').reverse() + lineDelimiter;
};
});
}
});
}
})
console.log('converted to CSV')
return result;
callback();
}

最大的问题是,目前 convertArrayObObjectsToCSVcreateLikeObject 函数完成之前运行。以为回调会起作用,但似乎我还没有得到一些完全正确的东西。

最佳答案

这可能是一种方法,因为您正在使用 get 调用,我已修改为根本不使用 Promise,因为 ajax 无论如何都会返回 Promise。

这是一个伪代码,您可能需要对其进行一些调整才能使其运行

function pageThroughLikes(facebookPostArray) {
var testArray = []
var promsieList = []
facebookPostArray.forEach(function(array) {
array.forEach(function(innerObject) {
if ('likes' in innerObject) {
if ('paging' in innerObject.likes) {
if ('next' in innerObject.likes.paging) {
nextPage = innerObject.likes.paging.next;
currentPostId = innerObject.id;
currentDataLength = innerObject.likes.data.length;
i = 0;
do{
promsieList.push(
$.ajax({url : nextPage
}))
i += 1;
} while (currentDataLength != 0 && i > 10)
}
}
}
})
});
console.log('paged through likes')
return promiseList();
}

processData = function(nextLikePageData){
likeData = {};
likeData.id = currentPostId;
likeData.likes = {};
likeData.likes.data = nextLikePageData.data
likeData.likes.paging = nextLikePageData.paging
console.log(likeData)
testArray.push(likeData);
facebookPostArray.push(testArray);
console.log('pushed to postArray')
return likeData;
}

$(document).ready(function() {
getPostLikes().then(function() {
$.when.apply(this, pageThroughLikes(postArray)).done(function() {
//debug to examine the arguments object, you'll notice its an array of arrays
var testArray = []
$.each(arguments, function(k, v){
var dt = processData(v[0]);
testArray.push(dt);
facebookPostArray.push(dt);
});
console.log(testArray)
test(testArray); // OR
test(facebookPostArray);
});
});
});

function test(postArray) {
var convertedPostCSV = convertArrayOfObjectsToCSV(postArray);
downloadCSV(convertedPostCSV);
}

编辑:

  • 参数是 jquery $.when 返回的默认对象功能。
  • 这是子数组的集合,每个子数组由数据组成,状态和 promise 对象。
  • 我假设您需要合并所有获取的数据调用一个 testArray 所以,这就是在 time 中所做的事情打电话

关于javascript - 为什么我的 Promise 没有同步运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40723012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com