![](/img/trans.png)
[英]What is the problem in this loop inside a constructor function? [JS]
[英]JS/NodeJS Problem with loop inside async function
我对这段代码有疑问:
async getDomains (req, res) {
try {
let domains = await Domain.findAll({ raw: true })
for(domain of domains) {
console.log('1')
var options = {
host: domain.name,
port: 443,
method: 'GET'
};
var request = https.request(options, (res) => {
console.log('2')
console.log('iam here')
domain.ssl = {
'valid_until': res.connection.getPeerCertificate().valid_from
}
});
console.log('3')
request.end();
}
console.log('4')
res.send(domains)
} catch(err) {
res.status(400).send({
error: err
})
}
},
output 应该是 1、2、3、4,但我得到的是 1、3、4、2。
有谁知道如何实现这一目标?
您已经为request
提供了回调,因此它将发送请求并继续前进,只有在收到响应后才记录2
。 您需要使用某种Promise
或async
/ await
来等待您的请求的响应。
var request = await (new Promise((resolve, reject) => {
https.request(options, (res) => {
console.log('2');
console.log('i am here');
domain.ssl = { /* stuff */ };
resolve();
});
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.