如何在 lambda nodejs 中处理异步调用

how to handle async call in lambda nodejs

我正在 lambda 中使用 nodejs 创建一个国际象棋引擎,但由于异步调用,它每次都在 lambda 上显示超时错误。这只是功能的一部分。它在本地 nodejs 控制台上运行良好,但在 lambda 上运行不正常。请有人提出建议,因为我是新手。

var chessjs = require('./chess');
var engine = require('uci');
var uciengine = new engine(process.env['LAMBDA_TASK_ROOT'] + '/stockfish');
var fs = require("fs");
var match;

function moveEngine() {
var curfen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
var depth = '20';

uciengine.runProcess().then(
        () => {
    console.log("Started.");
    return uciengine.uciCommand();
}
).then(
        () => {
    console.log("Is Ready?");
    return uciengine.isReadyCommand();
}
).then(
        () => {
    console.log("New game.");
    return uciengine.uciNewGameCommand();
}
).then(
        () => {
    console.log("Setting position.");
    return uciengine.positionCommand(curfen);
}
).then(
        () => {
    console.log('Starting position set');
    console.log('Starting analysis');
    return uciengine.depthLimitedGoCommand(depth, (info) => {
    });
}
).then((bestmove) => {
    console.log('Bestmove: ');
    console.log(bestmove);
    return uciengine.quitCommand();
}).then(() => {
    console.log('Stopped');
   response.sessionAttributes = {};
   context.succeed(response);
}).done();
}

  async call code
var chessjs = require('./chess');
var engine = require('uci');
var async= require('async');
var uciengine = new engine('/var/task/stockfish');
var fs = require("fs");
var match;

function moveEngine() {
   var curfen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
   var depth = '20';

async.auto({
runProcess: function(next, results) {
    uciengine.runProcess(next,results);
},
checkUiEngineReady:['runProcess',function(next,results) {
  uciengine.checkUiEngineReady(next,results);
}],
newGameCommand:['checkUiEngineReady',function(next,results) {
  uciengine.newGameCommand(next,results);
}],
position:['newGameCommand',function(next,results) {
  uciengine.positionCommand(curfen,next,results);
}],
godepth:['position',function(next,results) {
  uciengine.depthLimitedGoCommand(depth,next,results);
}]
}, function(err, response) {
if (err) {
    next(err);
} else {
    console.log(response);
    uciengine.quitCommand();
    context.succeed(response);
}
});
}
moveEngine();

异步调用给出了与以前相同的错误,我认为这可能是错误的。

您可以使用 async npm 模块在 Lambda 中处理异步调用,这是一个在 Nodejs 中处理异步编程的实用模块。

您可以使用 npm install --save async 安装异步模块。

async.auto 函数将有助于管理上述调用。

这是一个示例,您可以通过它来管理您的代码。

async.auto({
    runProcess: function(next, results) {
        runProcess(next,results);
    },
    checkUiEngineReady:['runProcess',function(next,results) {
      checkUiEngineReady(next,results);
    }],
    newGameCommand:['checkUiEngineReady',function(next,results) {
      newGameCommand(next,results);
    }]
}, function(err, response) {
    if (err) {
        next(err);
    } else {
        context.succeed(response);
    }
});

谢谢