在单独的函数中使用节点中的回调结果

Using results of a callback in node in a separate function

本文关键字:节点 回调 结果 函数 单独      更新时间:2023-09-26

我可能在这里错过了一点,所以我正在寻求建议。

我有一个nodejs服务器,它正在监听客户端连接,并根据收到的数据,调用API。

对该API的第一次调用获得一个ID,该ID需要在后续调用中使用以将它们分组在一起。

我正在努力的地方是对API的调用必然是异步的,并且在回调中我将ID分配给变量。当API服务器正在处理异步调用时,更多的数据从客户端传入,需要更多的API调用,但是我不能触发它们,直到我知道第一次调用的结果,因为第二次调用依赖于它。

正确的处理方法是什么?我觉得我应该使用Q来保证第一个API调用的结果给第二个API调用,但我不确定它应该如何构建。或者我应该将API调用排队,直到第一个调用完成?我该怎么做呢?

示例问题代码:

var server = net.createServer();
//set up the callback handler 
server.on('connection', handleConnection);
handleConnection(conn) {
  //do some stuff...
  firstAPICall();
  conn.on('data', handleData);
}
handleData(data) {
  //do some stuff...
  otherAPIcall();
}
firstAPICall() {
  client.get("http://myAPI/getID", function (data, response) {
    conn.myID = data[0].myID;
    }
  }
}
otherAPICall() {
  //How do I make sure I actually have a value
  //in conn.myID from the first function???
  client.post("http://myAPI/storeData", { data: {myID:conn.myID, data:someData} }, function (data, response) {
    //do some stuff...
    }
  }
}

是的,您应该为此使用承诺。为第一次调用异步解析的id做一个承诺,然后在随后的调用中使用它:

handleConnection(conn) {
  //do some stuff...
  var idPromise = firstAPICall();
  conn.on('data', function handleData(data) {
    //do some stuff...
    otherAPIcall(idPromise).then(function(result) {
      …
    });
  });
}
firstAPICall() {
  return Q.Promise(function(resolve, reject) {
    client.get("http://myAPI/getID", function (data, response) {
      resolve(data[0].myID);
    });
  });
}
otherAPICall(idPromise) {
  return idPromise.then(function(myID) {
    return new Promise(function(resolve, reject) {
      client.post("http://myAPI/storeData", {
        data: {myID:myID, data:someData}
      }, function (data, response) {
        //do some stuff...
        resolve(…);
      });
    });
  });
}

也许你应该在一个额外的函数中为client.get调用的结果创建一个承诺。还要确保在那里正确地处理错误,并使用它们调用reject。如果client将使用节点回调约定,Q甚至有一些很好的辅助函数。

尝试使用承诺。然后使用' Then '调用otherAPICall()

我想你可以假设他们将在连接后立即发送数据。你可以简化并检查otherAPICall如果你有ID,如果没有,你可以使用回叫。Promises或async/await关键字可能会使事情变得更好,但这不是必需的。

var server = net.createServer();
//set up the callback handler 
server.on('connection', handleConnection);
handleConnection(conn) {
  conn.on('data', handleData(connm, data));
}
handleData(conn, data) {
  //do some stuff...
  otherAPIcall(conn);
}
checkID(conn, cb) {
  if (!conn.myID) {
    client.get("http://myAPI/getID", function (data, response) {
      conn.myID = data[0].myID;
      cb();
    });
  } else {
    cb();
  }
}
otherAPICall(conn) {
  checkID(conn, function() {
    client.post("http://myAPI/storeData", { data: {myID:conn.myID, data:someData} }, function (data, response) {
      //do some stuff...
    });
  });
}

承诺可以链接值,并且总是在回调发生后使用返回值进行解析,

function async(value) { 
var deferred = $q.defer();
var asyncCalculation = value / 2;
deferred.resolve(asyncCalculation);
return deferred.promise;
}
var promise = async(8) 
.then(function(x) {
    return x+1;
})
.then(function(x) {
    return x*2;
})
.then(function(x) {
    return x-1;
});
promise.then(function(x) { 
console.log(x);
});

该值将通过所有成功回调,因此记录值9((8/2 + 1)* 2 - 1)。