Axios: chaining multiple API requests

前端 未结 7 749
失恋的感觉
失恋的感觉 2020-12-07 14:15

I need to chain a few API requests from the Google Maps API, and I\'m trying to do it with Axios.

Here is the first request, which is in componentWillMount()

7条回答
  •  时光取名叫无心
    2020-12-07 14:38

    create array of promise and then use reduce.

    /**
     * Runs promises from array of functions that can return promises
     * in chained manner
     *
     * @param {array} arr - promise arr
     * @return {Object} promise object
     */
    function runPromiseInSequence(arr, input) {
      return arr.reduce(
        (promiseChain, currentFunction) => promiseChain.then(currentFunction),
        Promise.resolve(input)
      )
    }
    
    // promise function 1
    function p1(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 5)
      })
    }
    
    // promise function 2
    function p2(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 2)
      })
    }
    
    // function 3  - will be wrapped in a resolved promise by .then()
    function f3(a) {
     return a * 3
    }
    
    // promise function 4
    function p4(a) {
      return new Promise((resolve, reject) => {
        resolve(a * 4)
      })
    }
    
    const promiseArr = [p1, p2, f3, p4]
    runPromiseInSequence(promiseArr, 10)
      .then(console.log)   // 1200
    

提交回复
热议问题