Tianhe Gao

JS 从回调函数中获取数据

最终 Node.js 代码:

 1whois.lookup(process.env.DOMAIN, (error, data) => {
 2  async function main() {
 3    // ...
 4
 5    // send mail with defined transport object
 6    let info = await transporter.sendMail({
 7      from: `tianheg <${user}>`,
 8      to: `域名邮箱 <${to}>`, // list of receivers
 9      subject: `今日 ${year}-${month}-${day} 测试`, // Subject line
10      text: data.slice(0, 936), // plain text body
11    });
12
13    // ...
14  }
15  main();
16});

我想将通过 whois 查到的域名信息 data 作为邮件的文本发送出去。但怎么也不得其道。最开始我是这样写的:

 1async function main() {
 2  // ...
 3
 4  // get whois info
 5  let whoisInfo;
 6
 7  whois.lookup(process.env.DOMAIN, function(err, data) {
 8    whoisInfo = data.slice(0, 936);
 9  });
10
11  console.log(whoisInfo)
12
13  // ...
14}
15
16main();

但是,怎么都得不到 whoisInfo,总是 undefined。我还找到一些讲异步编程的内容,但看得云里雾里。最终,我突然想到,能不能把主函数放到 whois.lookup 里面,于是就出现了开头的代码。刚好解决了我的需要。


No notes link to this note

Welcome to tell me your thoughts via "email"
UP