简体   繁体   中英

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

The while loops creates ethereum wallets, downloads robohash avatars according to the generated addresses and writes them to file. gLoops sets the amount of wallets created. I need the excution to wait for the avatar file to download and be written to file before continuing the while loop. I reckon it should be done with async/await but can't wrap my head around it

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

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

You can wrap your https.get() in a promise and use await to make the for loop pause for it to complete:

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

Alternately, you can use one of the http request libraries mentioned here that are already promise-aware and use them directly. My favorite in that list is the got() library and it supports streams for the way you are using it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM