如何在 parse.com 作业中创建和调用 httpRequest 函数?

How do I create and call the httpRequest function in a parse.com job?

我在云代码中创建了一个Job,并定义了一个云代码函数,它是一个http请求。如下所示,我在作业中定义了 http 请求,我可以 运行 这个作业成功,但是我无法让 httpRequest 函数打印到日志中,以查看代码实际上是运行。因此,我无法真正判断该作业是否正在使用 http 请求。我怎样才能让这个 http 请求打印到 parse.com 日志,以便我可以看到它确实在工作?

//lets define the job
Parse.Cloud.job("simpleGetRequest", function(request, response) {

//lets try to define the httpRequest function.
Parse.Cloud.define("httpRequest", function(request, response) {
    return Parse.Cloud.httpRequest({
            url: "https://data.seattle.gov/resource/y7pv-r3kh.json?$select=date_reported",
            success: function(httpResponse) {
                response.success(httpResponse.text);
                //console.log(httpResponse);
                //lets just see if we can get the console to do anyting
                console.log("we made it to this line")
            },
            error: function(httpResponse) {
                response.error('request failed with response code ' + httpResponse)
            }
    });
});
    //we need to call this response.success to make things happen. lets put this at the end always so we know if at least hte job is a success
    response.success("The scheduled job completed.");
});

您还可以做更多的事情来改进功能,但要回答具体问题,请重新排序控制台日志以在 调用响应成功之前执行 ,这会立即终止作业。 .

console.log(httpResponse);
//lets just see if we can get the console to do anyting
console.log("we made it to this line")
response.success(httpResponse.text);

此外,不要在函数的最后一行调用响应成功。这也是在 http 请求完成块有机会执行之前终止作业。

最后,不确定您是如何调用作业或函数的,但它的结构非常不寻常,将云函数的定义嵌套在作业中。您应该选择在您的应用程序(云函数)调用时是否要 运行 函数 系统按计划 运行 的函数(工作)。下面是每一个的样子(使用 promises,一旦你开始在云中异步地做更多的事情,这是一个必要的习惯)...

通过 "scheduling" 在解析网络应用程序上调用此作业...

Parse.Cloud.job("simpleGetRequest", function(request, response) {
    Parse.Cloud.httpRequest().then(function(httpResponse) {
        console.log(httpResponse);
        //lets just see if we can get the console to do anyting
        console.log("we made it to this line")
        response.success(httpResponse.text);
    }, function(httpResponse) {
        response.error('request failed with response code ' + httpResponse)
    });
});

从应用程序逻辑调用此函数,具体取决于哪个 sdk,具有多种 Parse.Cloud.run()...

Parse.Cloud.define("simpleGetRequest", function(request, response) {
    Parse.Cloud.httpRequest().then(function(httpResponse) {
        console.log(httpResponse);
        //lets just see if we can get the console to do anyting
        console.log("we made it to this line")
        response.success(httpResponse.text);
    }, function(httpResponse) {
        response.error('request failed with response code ' + httpResponse)
    });
});