NodeJs按顺序步骤调用模块

时间:2017-07-10 14:55:20

标签: javascript node.js

我是Nodejs的新手,来自Java背景。我为这个长期问题道歉。我正在开发一个独立的Nodejs应用程序,它必须按顺序执行步骤。以下是步骤:

  

第1步:应用程序必须调用external-server-A或者重试

     

第二步:上述通话成功后,必须致电   external-server-b通过在Step1上获取响应,或者重试。

     

Step3:上述调用成功后,必须调用本地模块   通过响应step2并调用函数。

不要结合1个JS页面中的所有步骤,我想在不同的JS页面中编写与上述步骤相关的函数,并通过require()导入它们。我不知道如何按顺序调用它们。 我应该在step1函数和step2函数的回调代码块中使用require(./step2)require(./step3)

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您需要在页面顶部要求step2和step3,但将它们公开为可以在以后执行的功能。您还可以使用promises来帮助您编写异步代码。例如:

// Step one
const step2 = require('./step2');
const step3 = require('./step3');

function someAsyncCallToExternalServerA() {
  /*
    Return a promise here which resolves to when
    your call to external server A call is successful
  */
}

someAsyncCallToExternalServerA()
  .then(function(serverAResults) { // I don't know if you need the serverA results or not

    // This will pass the results from the step2 success to the step3 function
    return step2.then(step3);
  })
  .then(function() {
    console.log('All done!');
  })
  .catch(function(err) {
    console.log('Failed: ', err);
  })

答案 1 :(得分:1)

一种方法是使用各种回调来根据需要触发您想要的内容。

想象一下两个步骤:

function step1(onSuccess, onError) {
     iDoSomethingAsync(function (err) {
         if (err) onError()
         else onSuccess()
     }
}
function step2(onSuccess, onError) {
     iDoSomethingElseAsync(function (err) {
         if (err) onError()
         else onSuccess()
     }
}

然后你可以简单地链接这样的呼叫:

step1(step2, step1)

第1步被调用,做某事,如果某事没有返回错误,它将调用step2。如果我们错了,它会再次调用step1。

在异步编程中,您必须了解当调用someFunc(回调)时,someFunc HAVN'T在下一行完成了他的工作。但是当调用回调时,somefunc将完成他的工作。

你可以通过回调做任何你想做的事情,因为你可以保证这个功能完成了他的工作(或者是错误的)

收回step1 / step2示例,这里是相同的函数,如果出现错误,则以1秒的延迟回调step1:

step1(step2, setTimeout.bind(this, step1, 1000))

一旦你以正确的方式思考,它就很简单了吗?如果你来自java,请考虑它是lambdas,Tasks和Futures / Promises之间的混合。

另外,正如另一个答案所指出的那样,使用像promise这样的库会帮助你编写更干净的代码(我推荐它,因为我的例子根本不干净),但你仍然需要了解一切是如何工作的。