我正在调用一个API并获取total_tweet_count。如果meta标记包含一个next_token,我用next_token获取下一个API (这里我调用相应的对象),并将total_tweet_count推送到一个数组中。但是,如果响应不包含next_token,我将停止迭代,只推送total_tweet_count并返回数组。由于某些原因,代码似乎不能运行。请帮帮忙。
下面的示例应该从res1获取next_token,然后调用res2并将tweet_count推入数组。然后使用res2的next_token,获取res3数据并推送计数。因为res3没有next_token,所以我们结束循环并返回数据。这就是我们的期望。敬请指教。
const getData = async () => {
const totalCount = [];
const results = await Promise.resolve(data.res1);
totalCount.push(results.meta.total_tweet_count)
do {
const results1 = await Promise.resolve(data[`res${results.meta.next_token}`]);
totalCount.push(results1.meta.total_tweet_count)
}
while (results.meta.next_token)
return totalCount;
}
getData().then(res => console.log(res))
我期望的最终输出是1,20,8
敬请指教。
发布于 2021-10-18 08:56:19
您的循环条件是常量:
const results = await Promise.resolve(data.res1);
//^^^^^^^^^^^^^
…
do {
…
}
while (results.meta.next_token)
你要找的是
const getData = async () => {
const totalCount = [];
let results = await Promise.resolve(data.res1);
totalCount.push(results.meta.total_tweet_count)
while (results.meta.next_token) {
results = await Promise.resolve(data[`res${results.meta.next_token}`]);
totalCount.push(results.meta.total_tweet_count)
}
return totalCount;
}
或
const getData = async () => {
const totalCount = [];
let results = {meta: {next_token: 1}};
do {
results = await Promise.resolve(data[`res${results.meta.next_token}`]);
totalCount.push(results.meta.total_tweet_count)
}
while (results.meta.next_token)
return totalCount;
}
请注意,这两个变量中都没有const results1
,而是对可变的results
变量进行了赋值。
发布于 2021-10-18 09:25:01
据我所知:
getData()
是一个作用于推特的完全同步的过程,因此不需要是asyncFunction
.data
的组合来创建推文计数的数组不需要使用.next_token
属性(除非它具有超出问题解释的某种秘密含义)。const getData = () => {
const keys = Object.keys(data); // array ['res1', 'res2', 'res3']
const totalCounts = keys.reduce((arr, key) => { // iterate the `keys` array with Array.prototype.reduce()
arr.push(data[key].meta.total_tweet_count); // push next tweet count onto the array
return arr; // return `arr` to be used in the next iteration
}, []); // start the reduction with empty array
return totalCounts; // [1, 20, 8]
};
在实践中,您将:
将data
传递给
data
const getData = (data) => {
return Object.keys(data).reduce((arr, key) => {
arr.push(data[key].meta.total_tweet_count);
return arr;
}, []);
};
https://stackoverflow.com/questions/69609456
复制