1

我有一系列需要Axios按顺序提出的请求。

let {files} = this.state, requestQueue = [];
files.forEach(file => requestQueue.push(makeRequest(file.name)));
requestQueue.reduce((curr, next) => {
  return curr.then(next);
}, Promise.resolve()).then((res) => console.log(res));

函数makeRequest如下

import Axios from 'axios';

let axiosCustom = Axios.create({
  baseUrl: 'localhost:8080',
  headers: {
    Accept: 'application/json'
  }
});

const makeRequest = (title) => {
  return axiosCustom({
    url: '/api',
    method: 'PUT',
    params: {
      title
    }
  });
};

响应只是第一个解决的。我该如何解决?

4

2 回答 2

1

这就是同步使用数组链接 axios 的方式。

const axios = require('axios');
function makeRequestsFromArray(arr) {
    let index = 0;
    function request() {
        return axios.get('http://localhost:3000/api/' + index).then(() => {
            index++;
            if (index >= arr.length) {
                return 'done'
            }
            return request();
        });

    }
    return request();
}

makeRequestsFromArray([0, 1, 2]);
于 2018-03-20T06:08:07.403 回答
0

我的理解是.then()需要一个函数来执行。它的行为将根据该函数的返回值(如果它的thenable)而改变。

因此,您需要更改您的 reduce 以提供.then将返回的方法next

let {files} = this.state,
    requestQueue = files.map(file => makeRequest(file.name));

requestQueue.reduce((curr, next) => {
  return curr.then(() => next); // <- here
}, Promise.resolve())
    .then((res) => console.log(res));

或者

requestQueue.reduce((curr, next) => curr.then(() => next), Promise.resolve())
    .then((res) => console.log(res));
于 2016-08-03T08:04:00.630 回答