繁体   English   中英

在继续 for 循环之前等待 HTTP 请求中的回调 function 完成

[英]Wait for completion of callback function in HTTP request before continuing with for loop

我正在尝试使用内置的 HTTPS 库在 node.js 中运行 HTTP 请求 3 次,每次运行都有一组不同的选项。 为了在一次执行完成后继续下一组选项,我使用了一个 for 循环,每次运行递增一次,总共运行 3 次。但是,不是等待每次运行完成后再继续在循环中,它完全跳过前两个调用,并使用第三组选项运行 3 次。我已经到处寻找答案,有人有任何想法/解决方案吗?

    for(let i = 0; i < 3; i++) {
        option = i;
        console.log("Calling with option " + i)
        await http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "\nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")

                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "\nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "\nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
            });
        }).end();
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    }

您可以将其包装在 promise 中,然后等待它:

for(let i = 0; i < 3; i++) {
    option = i;
    console.log("Calling with option " + i)
    await new Promise((resolve, reject) => {
        http.request(options[i], res => {
            let resp = '';
            res.on('data', function(chunk) {
                resp += chunk;
            });
            res.on('end', async function () {
                let data = await JSON.parse(resp);
                if(option === 0) { //Bloxlink handler
                    console.log("Case 1: Bloxlink")
                    if(data.status === "error") {
                        returndata += "Bloxlink returned no users"
                    } else {
                        returndata += "\nBloxlink returned user with ID " + data.primaryAccount + " and username " + await noblox.getUsernameFromId(parseInt(data.primaryAccount)) + "."
                    }
                } else if(option === 1) { //RoWifi handler
                    console.log("Case 2: RoWifi")
    
                    if(data.success === false) {
                        returndata += "RoWifi returned no users"
                    } else {
                        returndata += "\nRoWifi returned user with ID " + data.roblox_id + " and username " + await noblox.getUsernameFromId(data.roblox_id) + "."
                    }
                } else if(option === 2) { //Eryn handler
                    console.log("Case 3: Eryn")
                    if(data.status === "error") {
                        returndata += "Eryn returned no users"
                    } else {
                        returndata += "\nEryn returned user with ID " + data.robloxId + " and username " + data.robloxUsername + "."
                    }
                }
                console.log(returndata);
                resolve();
            });
            res.on('error', function () {
                channel.send('One or more APIs returned an error. The operation has been terminated.')
                reject();
            });
        }).end();
    }).then(() => {
        channel.send("Run " + i + " finished: " + returndata);
        console.log(returndata);
    });
}

但更简洁的方法是使用基于承诺的请求库,如fetchaxios

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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