如何将Waterfall方法转换为promise

时间:2017-04-14 09:03:53

标签: javascript node.js callback promise waterfall

下面是使用async-waterfall方法的代码段。我怎样才能使用诺言转换它。

async.waterfall([
    function(callback){
     User.update({username: user.username}, {$set: update_list}, function(err, a_user) {
      if (err) {
        err = new Error();
        err.code = 400;
        err.message = "Unexpected error occurred."
        callback(err)
      }
      if (!a_user) {
        err = new Error();
        err.code = 400;
        err.message = "User not found."
        callback(err)
      }else{
        callback(null, "updated", user_image);
      }
    })
   }, function(message, user_image, callback){
    if(user_image == undefined){
      callback(null, "done")
    }else{
      Bean.update({username: user.username, status:"Active"}, {$set: {user_image:user_image}},{multi:true},function(err, beanUpdated){
        if(err){
          err = new Error();
          err.code = 400;
          err.message = "Unexpected error occurred."
          callback(err)
        }else{
          callback(null, "done"); 
        }
      })
    }
  }
  ], function(err, result){
    if(err){
      return res.json({code:err.code, message:err.message})
    }else{
      return res.json({code:200, message:"Successfully updated profile."})
    }
  })

我通常使用异步模块的瀑布和系列方法来同步我的Node js代码。帮助我从异步切换到承诺。

1 个答案:

答案 0 :(得分:6)

我不会为你重写你的代码,但我会为你提供足够的信息,以便你可以用3种不同的风格自己做,并举例说明这些概念。重写代码将为您提供熟悉承诺的好机会。

您可以使用函数返回承诺,而不是函数进行回调并使用async.waterfall进行组合,并从then回调中返回这些承诺,在下一个then回调中使用这些承诺的已解析值:

f1().then((a) => {
  return f2(a);
}).then((b) => {
  return f3(b);
}).then((c) => {
  // you can use c which is the resolved value
  // of the promise returned by the call to f3(b)
}).catch((err) => {
  // handle errors
});

在这个简单的例子中可以简化为:

f1()
  .then(a => f2(a))
  .then(b => f3(b))
  .then((c) => {
    // use c here
  }).catch((err) => {
    // handle errors
  });

甚至这个:

f1().then(f2).then(f3).then((c) => {
  // use c here
}).catch((err) => {
  // handle errors
});

或者您可以使用async / await

轻松地将它们组合在一起
let a = await f1();
let b = await f2(a);
let c = await f3(b);
// ...

在这个特殊情况下甚至可以这样:

let c = await f3(await f2(await f1()));

您可以使用try / catch处理错误:

try {
  let c = await f3(await f2(await f1()));
  // use the c here
} catch (err) {
  // handle errors
}

使用await的代码必须在使用async关键字声明的函数内部,但您可以通过包装这样的内容在任何地方使用它:

// not async function - cannot use await here
(async () => {
  // this is async function - you can use await here
})();
// not async function again - cannot use await

(async () => { ... })()表达式本身返回一个promise,该promise被解析为异步函数的返回值,或者被抛出的异常被拒绝。

请注意,在上面的示例中,每个函数都可以轻松地依赖于前一个函数返回的已解析promise的值,即async.waterfall的确切用例,但我们不使用任何库。 ,只有该语言的原生特征。

{v}。{+ 1}}语法在Node v7.0 +中可用,带有和声标志,v7.6 +没有任何标志。参见:

有关更多示例,请参阅此答案:

有关更多背景,请参阅此答案的更新以获取更多信息: