【问题标题】:make an api request for each element on a list为列表中的每个元素发出 api 请求
【发布时间】:2019-07-14 02:14:14
【问题描述】:

我有这个功能:

updateCustomers = (input) => {

   //let urls = input;

   let urls = [{
    name: "localhost:8081",
    url: "http://localhost:8081"
},
{
    name: "localhost:8082",
    url: "http://localhost:8081"
},
{
    name: "localhost:8083",
    url: "http://localhost:8081"
}]

    const allRequests = urls.map(url => {

        let paramsNode = {
            customer: this.props.match.params.customer,
            environment: this.props.match.params.environment,
            action: 'check',
            node: url.name
        }

        sleep(2000).then(() => {
            this.gatewayService.manageServices(paramsNode).then((response) => {
                console.log("return " + response)
            })
        })

    })

    Promise.all(allRequests).then (function(results) {
        // API results in the results array here
        // processing can continue using the results of all three API requests
        console.log("HERE "+results)
    }, function(err) {
        // an error occurred, process the error here
    });
}

我在这里要做的是只确保 api 调用是有序的,并且在另一个完成时只执行一个 api 调用。 但是当我运行我的代码时,它并没有做我想要的。

这是我得到的照片:

HERE ,,

RestUtils.js:13 fetchJsonFromApi {"exitCode":"0"}

RestUtils.js:13 fetchJsonFromApi {"exitCode":"0"}

RestUtils.js:13 fetchJsonFromApi {"exitCode":"0"}

HERE 打印应该显示我的 api 订单的返回值,但它是未定义的 (HERE {"exitCode":"0"},{"exitCode":"0"},{"exitCode":"0"})

这是我的 API 调用:

 manageServices=(params)=>{

    let url = this.baseUrl;

    if(params.customer == null || params.environment == null) {
        throw "The customer or environment parameter cant be null.";
    }

    url += "/" + params.customer + "/" + params.environment +  "/"+params.node  +"/configurations/manageServices/" + params.action;

    url = encodeURI(url);

    return RestUtils.fetchJsonFromApi(url);

}


static fetchJsonFromApi(url, callback) {
    return fetch(url)
        .then(response => response.json())
        .then(json => {
            console.log("fetchJsonFromApi " + JSON.stringify(json))
            // making callback optional
            if (callback && typeof callback === "function") {
                callback(json);
            }
            return json;
        })
        .catch(error => {
            console.log(error)
        });
}

我只是想确保在对方通话结束后我会拨打电话。

不带休眠功能的更新:

【问题讨论】:

  • 您传递给urls.map(...) 的回调函数不返回任何内容,这意味着allRequestsundefined 的数组。
  • 为什么需要一个 api 调用才能完成,然后再进行下一个调用?他们似乎并不相互依赖。如果您使用正确的承诺返回,将保持并行请求结果的顺序

标签: javascript reactjs promise


【解决方案1】:

添加以下 return 语句以将承诺链返回到您的 map() 数组

   return sleep(2000).then(() => {
 // ^^^^  returns sleep() promise to map array
      return this.gatewayService.manageServices(paramsNode).then((response) => {       
      // ^^^^^  returns promise to the sleep `then()`          
            console.log("return " + response)
            return response;
          // ^^^^^ resolves the inner then() with response object and 
          // resolves the above promises and gets passed to Promise.all()
        });
      });

我怀疑您的 sleep() 是试图解决实际上是由不正确/缺少returns 引起的排序问题。删除它并记录其他返回将正常工作

【讨论】:

  • 如果我删除睡眠,我的请求将同时完成,更新为带有图片的问题@charlietfl
  • 无论如何...所有睡眠将同时结束,因为map() 不会等待它们。回到我的问题,为什么你需要让它们串行而不是并行?
  • 那么我该如何强制请求等待前一个完成?
  • 你真的需要吗?它们在客户端代码中似乎并不相互依赖
【解决方案2】:

使用 async/await 循环调用,阻塞迭代直到每次调用完成:

const doCallsInOrder = async () => {
    const paramsNode_array = urls.map(url => ({
        customer: this.props.match.params.customer,
        environment: this.props.match.params.environment,
        action: 'check',
        node: url.name
    }))

    for (let i = 0; i < paramsNode_array.length; ++i) { // don't use a forEach
        const response = await this.gatewayService.manageServices(paramsNode_array[i])
        console.log("return " + response) 
    }
}
doCallsInOrder()

【讨论】:

  • 为什么要事先创建一个包含所有参数的数组,而您可以在需要时简单地构造每个参数对象?
  • 你是对的,没有必要。我只是想尽可能地遵守 OP 的原始代码。您只想确保在 for 循环中迭代 urls 数组,而不是 Array.mapArray.forEach,因为这会使 async/await 变得复杂
猜你喜欢
  • 2021-12-04
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多