Javascript 在JS中登录到控制台之前,等待所有http GET请求完成
Javascript/节点noob在这里。在理解JS的整个异步方面有一些困难。我正在构建一个小应用程序,其目的是调用外部API,然后存储结果以用于日志记录 无论如何,我有一个GET请求,看起来像这样Javascript 在JS中登录到控制台之前,等待所有http GET请求完成,javascript,node.js,asynchronous,node-request,Javascript,Node.js,Asynchronous,Node Request,Javascript/节点noob在这里。在理解JS的整个异步方面有一些困难。我正在构建一个小应用程序,其目的是调用外部API,然后存储结果以用于日志记录 无论如何,我有一个GET请求,看起来像这样 request(callsOptions) .then(function (res) { //Request success... do some logic with the response object var content = JSON.stringify(res)
request(callsOptions)
.then(function (res) {
//Request success... do some logic with the response object
var content = JSON.stringify(res)
//save result to a file with the name as m-d-yyyy.json
fs.writeFile(`callLogs/${month}-${day}-${year}.json`, content, 'utf8', function (err) {
if (err) {
return console.log(err);
}
})
//get session_ids and call destinations and store in the 2 diff arrays
var calls = res.calls
for(let x = 0; x < calls.length; x++){
session_ids[x] = calls[x].session_id
dests[x] = calls[x].dest
}
//make an individual req for each call in the array
for(let x = 0; x < calls.length; x++){
getCallLog(session_ids[x], dests[x])
}
}).catch(function (err) {
//Request failure...
console.log('Whoops... something went wrong with the calls request!')
})
}
所以,我想等到所有GET请求完成后再进行一些逻辑处理。就目前而言,这种逻辑只会是这样的
console.log('DONE')
问题是,由于JS的异步特性,我所尝试的一切都会在完成之前显示完成。所以,我只是等了一会儿,以确保所有的请求都已完成
我尝试过的事情:
在for循环中放置if语句,以便在循环完成时使用
在getCallLog.then函数中使用计数器
编辑:像这样
const { promisify } = require("util")
只需返回内部函数的承诺,并承诺文件写入:
const { promisify } = require("util");
function getCallLog(id, dest){
return request(constructURL(id)) // <-- return the promise
.then(function (res) {
//Request success... do some logic with the response object
console.log('Request success!')
var content = JSON.stringify(res)
return promisify(fs.writeFile)(`${dest}/${id}.json`, content, 'utf8');
}).catch(function (err) { // also catches writing errors
console.log('Whoops... something went wrong with the call request!')
});
}
现在你可以添加一个。然后。。。到随后将执行的链:
.then(() => console.log("All done!"));
这有帮助吗?对不起,我有点困惑。当你说将承诺返回到链中时,你的确切意思是什么?@otterjesus我不确定我是否执行了错误,但在所有请求解决之前,它似乎仍然在控制台中发送。有关详细信息,请参见OP中的编辑code@otter您必须返回请求!!哦哎呀!非常感谢!!
const { promisify } = require("util");
function getCallLog(id, dest){
return request(constructURL(id)) // <-- return the promise
.then(function (res) {
//Request success... do some logic with the response object
console.log('Request success!')
var content = JSON.stringify(res)
return promisify(fs.writeFile)(`${dest}/${id}.json`, content, 'utf8');
}).catch(function (err) { // also catches writing errors
console.log('Whoops... something went wrong with the call request!')
});
}
const promises = [];
for(let x = 0; x < calls.length; x++){
promises.push(getCallLog(session_ids[x], dests[x]));
}
return Promise.all(promises);
.then(() => console.log("All done!"));