Node.js中的异步OR步骤 [英] async OR step in Node.js

查看:54
本文介绍了Node.js中的异步OR步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使我的异步代码与node.js一起使用

I'm not able to get my asynchronous code working with node.js

尝试异步和步骤库-代码仅返回第一个函数(其余函数似乎没有).我在做什么错了?

Trying both async and step libraries -- the code only returns the first function (doesn't seem to go through the rest). What am I doing wrong?

谢谢!

var step = require('step');
step(
function f1(){
        console.log('test1');
},
function f2(){
        console.log('test2');
},
function finalize(err) {
    if (err) { console.log(err);return;}
    console.log('done with no problem');
  }
);

或此

var async = require('async');
async.series([
function f1(){
        console.log('test1');
},
function f2(){
        console.log('test2');
},
function finalize(err) {
    if (err) { console.log(err);return;}
    console.log('done with no problem');
  }
]);

推荐答案

Step.js期望每个步骤都有回调.同样,使用Step的函数应回调结果,而不返回结果.

Step.js is expecting callbacks for each step. Also the function that is using Step should callback with the result and not return it.

因此,假设您拥有:

function pullData(id, callback){
  dataSource.retrieve(id, function(err, data){
    if(err) callback(err);
    else callback(data);
  });
}

使用步骤"的方式如下:

Using Step would work like:

var step = require('step');

function getDataFromTwoSources(callback){
  var data1,
    data2;
  step(
    function pullData1(){
      console.log('test1');
      pullData(1, this);
    },
    function pullData2(err, data){
      if(err) throw err;
      data1 = data;
      console.log('test2');
      pullData(2, this);
    },
    function finalize(err, data) {
      if(err)
        callback(err);
      else {
        data2 = data;
        var finalList = [data1, data2];
        console.log('done with no problem');
        callback(null, finalList);
      }
    }
  );
};

这将使它继续进行下去.

This would get it to proceed through the steps.

请注意,我个人更喜欢异步的原因有两个:

Note that I personally prefer async for two reasons:

  • Step捕获所有抛出的错误并对其进行回调;当这些库仅应清理代码外观时,这会更改应用程序的行为.
  • 异步具有更好的组合选项,外观更简洁

这篇关于Node.js中的异步OR步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆