簡體   English   中英

在繼續之前等待節點完成從 https.get 響應寫入文件?

[英]Wait for node to finish writing file from https.get response before continuing?

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++;
}

嘗試為您的函數使用異步等待功能?

您可以將https.get()包裝在一個 promise 中,並使用await使for循環暫停以使其完成:

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 請求庫之一,這些庫已經是承諾感知的並直接使用它們。 該列表中我最喜歡的是got()庫,它支持您使用它的方式的流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM