node.js - 如何在节点启动期间主要等待?
问题描述
想要从异步调用初始化一个值,然后继续使用该值,我不知道如何在节点加载其他代码之前等待。
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 --------------
解决方案
我不确定我明白你的意思,但也许这就是你想要的?
async function main() {
const response = await requestAsync.get('https://n...');
const headers = response.headers;
console.log('some other stuff here');
}
main();
将所有内容放在“主”函数中,您可以在执行任何其他操作之前等待您的初始请求。
不过要小心:这是阻塞的,所以如果请求需要一段时间,在完成之前不会在你的代码中发生任何事情。
推荐阅读
- android - Android Cmake 构建命令失败
- python - 执行 kmedoids python 模块
- python-3.x - create a new csv file in new subdirectory python 3.6
- ios - 如何在执行 segue 之前检查服务器响应值
- java - 子类不是抽象的,不会覆盖抽象方法 compareTo()
- audit - 如何设置 Kubernetes (v1.9.5) 审计基于 coreos (1688.5.3)
- angular - 遍历字符串数组
- c# - c# 选择父节点,并在datagridview中显示所有子节点
- python-2.7 - 使用 python 2.7 在单行中返回 JSON 记录
- python - 我怎样才能让我的端口扫描仪工作