【问题标题】:Chaining of array promises in AxiosAxios 中的数组 Promise 链接
【发布时间】:2016-12-08 19:25:22
【问题描述】:

我需要按顺序使用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
    }
  });
};

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

【问题讨论】:

  • 实际上你需要使用requestQueue.push(() => makeRequest(file.name))) 才能工作
  • @Bergi 这将委托创建承诺,但在减少方面应该与我的行为相同。您创建一个返回承诺的方法,我有一个承诺数组并传递then 一个返回承诺的方法。除非我遗漏了什么,唯一的区别是承诺何时执行?
  • @ste2425:是的,这就是区别。但是 OP 说他希望它们按顺序执行……就目前而言,他本可以使用 Promise.all(requestQueue)
  • @Bergi 啊,好吧,总是想问我是否错过了一些东西以努力学习。我认为 OP 意味着串行顺序这就是我保留 reduce 的原因,但这会并行顺序执行它们,所以一切都很好。
  • 我的意思是按顺序,第一个 promise 解决,然后开始第二个。 Promise.all 将异步运行它们。道歉,如果它是模棱两可的。 P1 执行并解析,P2 启动等等。

标签: javascript promise ecmascript-6 es6-promise axios


【解决方案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]);

【讨论】:

    【解决方案2】:

    我的理解是.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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 2016-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多