gpt4 book ai didi

javascript - 你如何使用 JS Promises 在 API 返回值时继续从 API 请求?

转载 作者:行者123 更新时间:2023-11-30 14:47:09 24 4
gpt4 key购买 nike

我试图在 API 继续返回时继续从 API 请求。我正在使用 LaunchLibrary API ( https://launchlibrary.net/docs/1.3/api.html ),我正在尝试请求上个月的启动。

API 返回总共 15 个结果,但只显示前 10 个。要获得接下来的 5 个,您向请求传递一个偏移量并再次查询(“&offset=10”),这将为您提供接下来的五个。

我想做的是继续从 API 请求,同时传递偏移量,直到从 API 返回的计数为零。我正在尝试使用 javascript Promises 来完成此操作,但遇到了一些麻烦。

这是我简洁的“app.js” Node 文件的样子:

app.get("/recent", function(req, res){

var past_launches = [];
var offset = 0;
var count_return = 0;

var endDate = moment().subtract(1, "days");
var startDate = moment().subtract(1, "months").subtract(1, "days");

do {
var url = "https://launchlibrary.net/1.3/launch?startdate="+startDate.format("YYYY-MM-DD")+"&enddate="+endDate.format("YYYY-MM-DD")+"&offset="+offset+"&mode=verbose";
var past_launch_promise = new Promise(function(resolve, reject) {
request(url, function(err, response, body) {
if(!err && response.statusCode == 200) {
var data = JSON.parse(body);
resolve(data);
} else {
reject(Error(err));
}
});
}).then(function(result) {
count_return = result.count;
offset = count_return;
past_launches.concat(result.launches);
}, function(err) {
console.log(err);
});
} while(count_return >= 10);

res.render("recent",{data:promises, embed:embed, status:status});
});

我明白问题出在哪里:由于请求是异步的,它会在实际返回之前达到 while,并且由于 count_return 最初为 0,它只是在返回任何内容之前停止。我认为使用 promises 和 .then() 函数我可以强制循环等待,但这显然不是真的。

这是我正在使用的查询 ( https://launchlibrary.net/1.3/launch?startdate=2018-01-11&enddate=2018-02-10&mode=verbose )。通过添加“&offset=10”,您可以获得下一页的启动。什么是解决这个问题的有效方法。

最佳答案

一种方法是使用递归(通常 not advisable 用于 JavaScript 中的无限循环或大循环,因为这些可能会导致...等等...堆栈溢出错误 🤣)。

const moment = require('moment');
const request = require('request-promise-native');

function getLaunches(startDate = moment().subtract(1, 'months').subtract(1, 'days'), endDate = moment(startDate).add(1, "months"), offset = 0, launches = []) {
const url = `https://launchlibrary.net/1.3/launch?startdate=${moment(startDate).format('YYYY-MM-DD')}&enddate=${moment(endDate).format('YYYY-MM-DD')}&offset=${offset}&mode=verbose`;

return request.get({
uri: url,
json: true
}).then((response) => {
const total = response.total;
launches.push(...response.launches);

if (launches.length < total) {
const nextOffset = offset + response.count;
return getLaunches(startDate, endDate, nextOffset, launches);
}

return launches;
});
}

getLaunches().then((launches) => console.log({
total: launches.length,
launches
}));

另一种方法是使用 async/await (在 Node 8+ 中受支持)。应该注意的是,这些仍然是实验性功能,但是这个答案是为了展示它们如何使异步代码读起来更像您示例中的同步代码。

const moment = require('moment');
const request = require('request-promise-native');

async function getLaunches(startDate = moment().subtract(1, 'months').subtract(1, 'days'), endDate = moment(startDate).add(1, "months"), offset = 0) {
let total = 0;
const launches = [];

do {
const url = `https://launchlibrary.net/1.3/launch?startdate=${moment(startDate).format('YYYY-MM-DD')}&enddate=${moment(endDate).format('YYYY-MM-DD')}&offset=${offset}&mode=verbose`;
const response = await request.get({
uri: url,
json: true
});

total = response.total;
offset += response.count;
launches.push(...response.launches);
} while (launches.length < total);

return launches;
}

getLaunches().then((launches) => console.log({
total: launches.length,
launches
}));

关于javascript - 你如何使用 JS Promises 在 API 返回值时继续从 API 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48736700/

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