【问题标题】:Wait for node to finish writing file from https.get response before continuing?等待节点完成从 https.get 响应写入文件,然后再继续?
【发布时间】:2021-07-29 11:34:59
【问题描述】:

while 循环创建以太坊钱包,根据生成的地址下载 robohash 头像并将其写入文件。 gLoops 设置创建的钱包数量。在继续while循环之前,我需要执行等待头像文件下载并写入文件。我认为它应该使用 async/await 来完成,但我无法理解它

let gLoops = 0;
while (gLoops < 10) {

pKey = crypto.randomBytes(32).toString("hex");
wallet = new ethers.Wallet(pKey);
address = wallet.address;

let url = urlBase + address;

https.get(url, (response) => {
    let filePath = `${arg1path}\\avatars\\${address}.jpg`;
    let stream = fs.createWriteStream(filePath);

    response.pipe(stream);
    stream.on("finish", () => {
        stream.close();
        console.log("Download Completed");
    });
});

gLoops++;
}

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您可以将https.get() 包装在一个promise 中并使用await 使forloop 暂停以完成:

    function processAvatar(pKey, wallet, address, url) {
        return new Promise((resolve, reject) => {
            https.get(url, (response) => {
                let filePath = `${arg1path}\\avatars\\${address}.jpg`;
                let stream = fs.createWriteStream(filePath);
    
                response.on("error", reject);
    
                stream.on("finish", () => {
                    stream.close();
                    console.log("Download Completed");
                    resolve();
                }).on("error", reject);
    
                response.pipe(stream);
    
            }).on("error", reject);
        });
    }
    
    
    async function run() {
        for (let gLoops = 0; gLoops < 10; ++gLoops)
            let pKey = crypto.randomBytes(32).toString("hex");
            let wallet = new ethers.Wallet(pKey);
            let address = wallet.address;
            let url = urlBase + address;
            await processAvatar(pKey, wallet, address, url);
        }    
    }
    
    run().then(() => {
        console.log("all done");
    }).catch(err => {
        console.log(err);
    });
    

    或者,您可以使用提到的 http 请求库之一 here 已经可以感知并直接使用它们。该列表中我最喜欢的是 got() 库,它支持您使用它的方式的流。

    【讨论】:

    • 非常感谢,这正是我所需要的。我会研究 Promise。 p.s.我认为 C/C++ 对于像这样的同步任务会是一个更好的选择
    • @bitbar - 我没有特别的理由知道为什么 C/C++ 在这方面会比 nodejs 更好。您只需要了解 promise 在 nodejs 中的工作原理并使用支持它们的 http 库即可。这对于现在的大多数 nodejs 编程来说都是必需的,所以它只是学习有效使用 nodejs 编程环境的东西。
    【解决方案2】:

    尝试为您的函数使用异步等待功能?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2019-11-01
      • 2021-05-06
      • 2021-05-21
      相关资源
      最近更新 更多