首页 文章

JS async /等待任务队列

提问于
浏览
3

在我的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 ...
    }

什么是处理异步返回的最佳方法?

1 回答

  • 2

    您可以保存先前的待处理承诺,等待它调用下一个 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)
    

相关问题