在我的JS应用中,我正在使用async / await功能。我想执行多个API调用,并希望将它们依次触发。换句话说,我想替换这个简单的方法:
const addTask = async (url, options) => { return await fetch(url, options) }
具有更复杂的内容。例如:
let tasksQueue = [] const addTask = async (url, options) => { tasksQueue.push({url, options}) ...// perform fetch in queue return await ... }
处理异步收益的最佳方法是什么?
答案 0 :(得分:4)
您可以保存上一个未完成的承诺,在调用下一个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)