首页 > 解决方案 > 如何在节点启动期间主要等待?

问题描述

想要从异步调用初始化一个值,然后继续使用该值,我不知道如何在节点加载其他代码之前等待。

console.log('---- initialize the value during startup ----');
const p1 = (async () => {
    const res = await requestAsync.get('https://nodejs.org/dist/latest-v8.x/docs/api/util.html');
    return res.headers;
})();
const v2 = p1.then(v => (v));

console.log(v2);
console.log('---------- more work after v2 is resolved --------------');

我明白了

---- initialize the value during startup ----
Promise { <pending> }
---------- more work after v2 is resolved --------------

标签: node.js

解决方案


我不确定我明白你的意思,但也许这就是你想要的?

async function main() {
  const response = await requestAsync.get('https://n...');
  const headers = response.headers;

  console.log('some other stuff here');
}

main();

将所有内容放在“主”函数中,您可以在执行任何其他操作之前等待您的初始请求。

不过要小心:这是阻塞的,所以如果请求需要一段时间,在完成之前不会在你的代码中发生任何事情。


推荐阅读