首页 > 解决方案 > 创建一个在 HTTP 请求完成之前产生的函数

问题描述

我可以被认为是 Node.JS 的新手,所以很抱歉,在这里我试图创建一个产生代码执行的函数,直到代码完成发出 HTTP 请求(使用“请求”npm 模块),然后将返回,问题是该库不产生代码执行,我尝试过使用promise,但它仍然不会产生代码执行。

原始代码:

const request = require("request")

// CONFIG
const ROBLOSECURITY = ""
var http_header = {
    "Cookie": ".ROBLOSECURITY="+ROBLOSECURITY
}

function MakeRbxReq(http_method, url, payload) {
    var jsonbody
    var retfunc = {}
    try {
        jsonbody = JSON.stringify(payload)
    } finally {}
    var options = {
        uri: "http://" + url,
        body: jsonbody || "",
        methpd: http_method,
        headers: http_header
    }

    request(options, function(_, res) {
        if (http_method.toUpperCase() == "POST" || http_method.toUpperCase() == "PUT" || http_method.toUpperCase() == "PATCH" || http_method.toUpperCase() == "DELETE") {
            if (res.headers["X-CSRF-TOKEN"]) {
                http_header["X-CSRF-TOKEN"] = res.headers["X-CSRF-TOKEN"]
                options["headers"] = http_header
                if (res.statusCode == 403) {
                    request(options, function(_, res) {
                        retfunc = {statusCode: res.statusCode, body: res.body}
                    })
                } else {
                    retfunc = {statusCode: res.statusCode, body: res.body}
                }
            }
        }
        retfunc = {
            statusCode: res.statusCode,
            body: res.body
        }
        return
    })

    return retfunc
}

console.log(MakeRbxReq("GET", "search.roblox.com/catalog/json?CatalogContext=2&Subcategory=6&SortType=3&SortAggregation=5&Category=6"))

承诺尝试:

const request = require("request")

// CONFIG
const ROBLOSECURITY = ""
var http_header = {
    "Cookie": ".ROBLOSECURITY="+ROBLOSECURITY
}

function MakeRbxReq(http_method, url, payload) {
    var jsonbody
    var retfunc = {}
    try {
        jsonbody = JSON.stringify(payload)
    } finally {}
    var options = {
        uri: "http://" + url,
        body: jsonbody || "",
        methpd: http_method,
        headers: http_header
    }

    async function req() {
        let reqPromise = new Promise(function(resolve, reject) {
            request(options, function(err, res) {
                console.log("resolving")
                resolve({statusCode: res.statusCode, body: res.body})
            })
        })
    }

    req()

    return retfunc
}

console.log(MakeRbxReq("GET", "search.roblox.com/catalog/json?CatalogContext=2&Subcategory=6&SortType=3&SortAggregation=5&Category=6"))

使用承诺的输出:

C:\Program Files\nodejs\node.exe .\index.js
{}
resolving

标签: javascriptnode.jsnode-request

解决方案


request (promise)异步的。

您应该与awaitthen

这里有一些例子


推荐阅读