【发布时间】: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(...)的回调函数不返回任何内容,这意味着allRequests是undefined的数组。 -
为什么需要一个 api 调用才能完成,然后再进行下一个调用?他们似乎并不相互依赖。如果您使用正确的承诺返回,将保持并行请求结果的顺序
标签: javascript reactjs promise