【发布时间】:2019-12-03 13:05:44
【问题描述】:
我已向 API 发出 HTTP PUT 请求,该 API 将响应状态返回为“等待”。我想继续使用 HTTP GET 请求轮询 API,直到状态变为“完成”。我在 NodeJS 中使用 Promise,但还没有找到持续轮询我的请求的解决方案。
我尝试过使用 setTimeout() 来使用 Promise Chaining,但这不会轮询 API,而是请求与我为 HTTP GET 编写代码一样多的次数。我想使用类似的东西:
while(JSON.parse(response.body).result.info.state != "finished")
{
//keep polling
}
我应该在 API 控制台上看到轮询 GET 请求,但 while 循环只运行一次。
startRequest(request, reply) {
console.log("startRequest() is fired")
return new Promise((resolve, reject) => {
setTimeout(function () {
Request.put({ //making a PUT request (i have done require('request'))
headers: {
"SessionID": request.payload.session
},
url: "http://" + API - IP + ":" + API - PORT + "/upload/" + request.payload.filenameWithoutExtension,
}, (error, response) => {
if (error)
reject(error);
else {
var state = JSON.parse(response.body).result.info.state;
var pendingid = JSON.parse(response.body).result.info.id;
console.log("response.body", response.body)
resolve(state + ":" + pendingid);
}
})
}, 3 * 1000)
}).then(response => { //then with response making a GET request
var infoArray = response.split(":")
var pendingid = infoArray[1];
return new Promise(function (resolve, reject) {
console.log("Polling() is fired")
while (state != "finished") {
Request.get({
headers: {
"SessionID": request.payload.session
},
url: "http://" + API - IP + ":" + API - PORT + "/pending/" + pendingid,
}, (error, response) => {
if (error)
reject(error);
else {
state = JSON.parse(response.body).result.info.state;
return state;
}
})
}
}
}
}
【问题讨论】:
-
@Bob 我想根据 HTTP PUT 请求中的响应发送重复的 HTTP GET 请求。通常响应是“等待”状态。我想触发相同的 HTTP GET 请求,直到我获得“完成”状态。
-
您不能将
while循环与异步内容一起使用(除非您使用async/await语法)。尝试递归方法。 -
@Bergi 在这种情况下如何使用 Async /await 语法?
-
@DevSenGoku Just like this
-
@Bergi 会试试这个并回复你。谢谢老兄。
标签: javascript node.js loops http promise