In my JS app I’m using the async / await feature. I would like to perform multiple API calls and would like them to be fired one after other. In other words I would like to replace this simple method:
JavaScript
x
4
1
const addTask = async (url, options) => {
2
return await fetch(url, options)
3
}
4
with something more complex.. like:
JavaScript
1
7
1
let tasksQueue = []
2
const addTask = async (url, options) => {
3
tasksQueue.push({url, options})
4
// perform fetch in queue
5
return await
6
}
7
What will be the best way to handle the asynchronous returns?
Advertisement
Answer
You could save previous pending promise, await for it before calling next fetch
.
JavaScript
1
24
24
1
// fake fetch for demo purposes only
2
const fetch = (url, options) => new Promise(resolve => setTimeout(resolve, 1000, {url, options}))
3
4
// task executor
5
const addTask = (() => {
6
let pending = Promise.resolve();
7
8
const run = async (url, options) => {
9
try {
10
await pending;
11
} finally {
12
return fetch(url, options);
13
}
14
}
15
16
// update pending promise so that next task could await for it
17
return (url, options) => (pending = run(url, options))
18
})();
19
20
addTask('url1', {options: 1}).then(console.log)
21
22
addTask('url2', {options: 2}).then(console.log)
23
24
addTask('url3', {options: 3}).then(console.log)