Nodejs/Javascript 回调用法 - 等待 API 调用

Nodejs/Javascript callback usage - Waiting for API call

我已经搜索和阅读了一段时间,但似乎无法理解如何仅通过回调实现以下目标。我知道这应该是 "simple" 并且不希望使用 promises 或任何其他库来解决它,因为我想了解如何仅通过回调来实现它。

我正在使用 Node.js 编写一个网络表单,如果没有提供 JIRA 事件编号,它将创建工单,然后发送带有编号的电子邮件通知。

我有的是...伪代码:

function jiraCreate(req, res) {
    if req.body.inc is blank {
        var jiraInc = jiraAPI call to create ticket;
    } else {
        jiraInc = req.body.inc;
    }
    return jiraInc;
}

function jiraComment(req, res, jiraInc) {
    jiraCommentAPI(jiraInc) // jiraAPI call to add comments to the provided jiraInc
}

function handleJira(req, res) {
    var jiraInc = jiraCreate(req, res);
    jiraComment(req, res, jiraInc);
}

handleJira(req, res);

当然,在上面,如果req.body.inc为空,jiraComment只会执行并声明事件不存在。我将如何使用回调重写它来实现我的目标?可能吗?

我已经阅读了很多关于回调的内容,但似乎无法理解。无论我如何编写代码,jiraComment 似乎总是 运行 首先。我非常感谢提供的任何帮助!

谢谢!

"jiraAPI call to create ticket" 是异步的...即当您进行调用时,代码类似于

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  var body = "";
  res.setEncoding('utf8');
  res.on('data', function(chunk) {
    body += chunk;
  });
  res.on('end', function() {
      // {1} Here you can continue with next step
  });
}).end();

您应该将下一步的代码放在 {1} 中。发出请求后立即按照您所做的那样放置是行不通的。