Last active
September 18, 2021 17:38
-
-
Save lucivaldo/4c31112eb62ca8ce327d61742b962c97 to your computer and use it in GitHub Desktop.
Exemplo de código JS para realizar várias chamadas assíncronas para API backend utilizando iterables e for await...of
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetchAllResources = async (resources, params) => { | |
const asyncIterable = { | |
[Symbol.asyncIterator]() { | |
return { | |
page: '1', | |
finished: false, | |
async next() { | |
if (!this.finished) { | |
const response = await api.get(resources, { | |
params: { ...params, page: this.page }, | |
}); | |
const nextPage = response.headers['x-next-page'] || ''; | |
this.finished = nextPage === ''; | |
this.page = nextPage; | |
return Promise.resolve({ | |
value: response, | |
done: false, | |
}); | |
} | |
this.page = '1'; | |
this.finished = false; | |
return Promise.resolve({ | |
done: true, | |
}); | |
}, | |
}; | |
}, | |
}; | |
let results = []; | |
for await (const resp of asyncIterable) { | |
const { data } = resp; | |
results = [...results, ...data]; | |
} | |
return results; | |
}; | |
export const getAllIssues = async milestone => { | |
const params = { | |
milestone, | |
per_page: 100, | |
scope: 'all', | |
sort: 'asc', | |
}; | |
return fetchAllResources('issues', params); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment