nodejs生成器异步回调 - 松弛统一云构建

时间:2016-06-02 15:48:28

标签: javascript node.js unity3d callback slack

我正在为我们团队的松弛渠道开发定制的统一云构建集成。并且坚持做出适当的回调。它似乎在asyc任务完成之前返回null,因此在进行正确的异步回调时需要一些帮助。我已经包含了脚本和console.log结果。



var request = require('request');
var config = require('../../config.js');
var slackManager = require('../slack/slackmanager.js');

module.exports = {
    AlertSlack: function (payload) {
        var getLink = GetLink(payload);
        console.log(getLink.next());
        slackManager.alertSlack(getLink.next().value);
    }
}

function* GetLink(payload) {
    try {
        var shareEndPointURL = config.unity.apibaseurl + payload.links.api_self.href + "/share";
        var shareID = yield HttpRequestHandler(shareEndPointURL, 'GET');
        
        //space to yield more httpRequest
        //space to yield more httpRequest
        //space to yield more httpRequest
        
        return " some final data ";
    } catch (e) {
        console.log("Exception : " + e);
        return e;
    }
}

function HttpRequestHandler(endpointURL, httpMethod) {
    var options = {
        url: endpointURL,
        method: httpMethod,
        headers: config.unity.unityAuthHeaders
    }
    request(options, function (err, resp, body) {
       console.log(body);
       return body;
    });
}




这是控制台日志



{ value: undefined, done: false }
<-----recived call in slackmanager.js with ### some final data ###----->
{"shareid":"dfgdfgszdffzc"}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案,我重新考虑了逻辑并制定了简单的事件处理程序。

  

因为我已经成功使用了异步回调,所以它是   毫无意义地在它上面制造不需要的发电机。

这是我提出的解决方案。比旧版本更简单,更干净。

var request = require('request');
var config = require('../../config.js');
var slackManager = require('../slack/slackmanager.js');

module.exports = {
    AlertSlack: function (payload) {
        var shareEndPointURL = config.unity.apibaseurl + payload.links.api_self.href + "/share";    
        HttpRequestHandler(shareEndPointURL, "GET", HandleShareID);
    }
}

function HttpRequestHandler(endpointURL, httpMethod, handler) {
    var options = {
        url: endpointURL,
        method: httpMethod,
        headers: config.unity.unityAuthHeaders
    }
    request(options, function(error, response, body) {
        handler(JSON.parse(body));
    });
}

function HandleShareID(result){
    var downloadURL = config.unity.downloadEndPointBase + result.shareid;
    HttpRequestHandler(downloadURL, 'GET', HandleDownLoadedData);
}

function HandleDownLoadedData(result) {
    slackManager.alertSlack(result);
}