对列表中的每个元素进行api请求

时间:2019-07-13 17:33:59

标签: javascript reactjs promise

我有这个功能:

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)
        });
}

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

没有睡眠功能的更新:

enter image description here

2 个答案:

答案 0 :(得分:0)

添加以下return语句以将promise链返回到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()试图解决订购问题,该问题实际上是由于return不正确/缺失而引起的。删除它并保持其他收益记录就可以了

答案 1 :(得分:0)

使用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()