2017-07-10 25 views
0

我对Nodejs非常陌生,来自Java背景。我为长期问题表示歉意。我正在开发独立的Nodejs应用程序,它必须按顺序执行步骤。下面是步骤:NodeJs在连续步骤中调用模块

Step1: The application has to call the external-server-A or else retry

Step2: Once the above call is success, it has to call external-server-b by taking the response on Step1 or else retry.

Step3: Once the above call is success, it has to invoke local module by taking the response-of-step2 and call a function.

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

在此先感谢您的帮助。

回答

2

您将需要在页面顶部的第2步和第3步,但将它们暴露为可在以后执行的功能。您也可以使用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); 
    }) 
+0

Andrew Lively:谢谢你的信息。我会读更多关于承诺。用承诺重试什么是最好的方法。 – John

+1

@John我会建议检查这个问题重试承诺:https://stackoverflow.com/questions/38213668/promise-retry-design-patterns –

+0

如果我必须从app.js文件中调用这些步骤和Step1的响应已传递给Step2然后我该如何做到这一点。 – John

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中被调用时,做一些事情,如果事情不返回错误,它会调用第二步。如果我们错误,它会再次调用step1。

在异步编程中,您必须明白,在调用someFunc(回调函数)时,someFunc会在下一行完成他的工作。但是当callback被调用时,somefunc将完成他的工作。

这是给你做任何你想要的回调,因为你guaranted该功能已完成了他的工作(或出错)

收回的第一步/ step2的例子,这里是相同的功能,调用以1秒的延迟回到第1步在错误的情况下:

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

一旦你认为正确的方式,这是很简单的,不是吗?如果你来自java,那么考虑它是lambdas,Tasks和Futures/Promises之间的混合体。另外,正如其他答案指出的那样,使用像promise这样的库将帮助您编写更干净的代码(并且我推荐它,因为我的示例根本不干净),但是您仍然需要了解每种方法的工作原理。

+0

感谢您的详细解释,它确实有帮助。关于链接调用和设置重试机制。十分感谢你分享这些信息。 – John