例如,假设您想要将API返回的分页数据存储到数据库中。
let db;
let pageitems = 35
var offset = 0;
dbConnect //establish connection to database
.then( fetch(apiLink+?offset=2)
.then( res => res.json())
.then( res => {
var total = res.count
return collection.insertMany(res.data, {ordered: false})
// If offset is less than total, I want to increase offset and go back to the fetch-event.
.catch( err => {
if(err.code !== 11000){log(err)}
else{log({completed: err.result.nInserted, duplicates:
err.result.result.writeErrors.length});}
})
.then(() => {
connection.close();
})
pageitems
(15)个项目?res.count
是获取的记录数还是后端数据集的总大小? - trincotfetch
,而不是在dbConnect
解析时调用。您必须在那里放置() => fetch(...
。 - trincotasync
/await
时,您当然可以使用循环。 - Bergi