Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  62] [ 7]  / answers: 1 / hits: 21596  / 6 Years ago, thu, november 29, 2018, 12:00:00

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:


const addTask = async (url, options) => {
return await fetch(url, options)
}

with something more complex.. like:


let tasksQueue = []
const addTask = async (url, options) => {
tasksQueue.push({url, options})
...// perform fetch in queue
return await ...
}

What will be the best way to handle the asynchronous returns?


More From » async-await

 Answers
9

You could save previous pending promise, await for it before calling next fetch.





// fake fetch for demo purposes only
const fetch = (url, options) => new Promise(resolve => setTimeout(resolve, 1000, {url, options}))

// task executor
const addTask = (() => {
let pending = Promise.resolve();

const run = async (url, options) => {
try {
await pending;
} finally {
return fetch(url, options);
}
}

// update pending promise so that next task could await for it
return (url, options) => (pending = run(url, options))
})();

addTask('url1', {options: 1}).then(console.log)

addTask('url2', {options: 2}).then(console.log)

addTask('url3', {options: 3}).then(console.log)




[#53012] Monday, November 26, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
;