[英]make an api request for each element on a list
我有這個功能:
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)
});
}
我只想確保對方通話結束后再打個電話。
沒有睡眠功能的更新:
添加以下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
s引起的。 刪除它並保持其他收益記錄就可以了
使用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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.