简体   繁体   English

如何将回调转换为承诺

[英]how to convert callback to promise

I'm trying to learn about what the promise is and how to convert callback to promise.我正在尝试了解承诺是什么以及如何将回调转换为承诺。 While I'm converting my code to promise I got very confused about the ref.当我将代码转换为 promise 时,我对 ref 感​​到非常困惑。 I would very appreciate it if you show me how to convert this code as a simple example.如果您向我展示如何将这段代码作为一个简单的例子进行转换,我将不胜感激。

database.ref('/users').on("child_added").then(function(snap){
  var subData = snap.val();

  database.ref('/subs/' + subData.subid + '/pri/' + snap.key).once("value").then(function(userSnap) {
    var userData = userSnap.val();

    subData.name = userData.name;
    subData.age = userData.age;

    database.ref('/subs/' + subData.subid).once("value",function(subDSnap) {
      var subDData = subDSnap.val();
      subData.type = subDData.type;
      database_m.ref('/users/' + snap.key).set(subData);
    });
  });  
});

A Promise is not a replacement for every type of callback; Promise 并不能替代所有类型的回调; rather it's an abstraction around one particular task that will either succeed once or fail once.相反,它是对一项特定任务的抽象,该任务要么成功一次,要么失败一次。 The code you're converting looks more like an EventEmitter, where an event can occur multiple times, so replacing .on('child_added', ...) with a Promise implementation is not a good fit.你将看起来更像是一个EventEmitter,其中,事件可能会出现多次的代码,所以更换.on('child_added', ...)并承诺实现不是一个很好的选择。

However, later on, you have a .once(...) call.但是,稍后,您有一个.once(...)调用。 That's a bit closer to a Promise in that it will only complete once.这更接近于 Promise,因为它只会完成一次。 So if you really wanted to convert that, here's what it could look like:所以如果你真的想转换它,它可能是这样的:

function get(database, url) {
  return new Promise(function (resolve, reject) {
    database
      .ref(url)
      .once('value', resolve)
      .once('error', reject);
  });
}

database.ref('/users').on("child_added", function(snap) {
  var subData = snap.val();

  get(database, '/subs/' + subData.subid + '/pri/' + snap.key)
    .then(function(userSnap) {
      var userData = userSnap.val();

      subData.name = userData.name;
      subData.age = userData.age;

      return get(database, '/subs/' + subData.subid);
    })
    .then(function(subDSnap) {
      var subDData = subDSnap.val();
      subData.type = subDData.type;
      database_m.ref('/users/' + snap.key).set(subData);
    })
    .catch(function (err) {
      // handle errors
    });
  });  
});

I am not sure I understand the question and if your "on" is returning a promise or just listening, but in your code you have nested '.then', which is not the common way to deal with promises and I am not sure that's what you wanted to achieve here.我不确定我是否理解这个问题,如果你的“on”是返回一个承诺或只是在听,但在你的代码中你嵌套了“.then”,这不是处理承诺的常用方法,我不确定那是你想在这里实现什么。

You could do (assuming that the on function returns a promise, which I doubt)你可以这样做(假设 on 函数返回一个承诺,我对此表示怀疑)

 database.ref('/users').on("child_added")
.then(function(snap){/* do something with the first part of your snap function*/})
.then (results => {/* do something else, such as your second ref call*/})
.catch(error => {/* manage the error*/})

To learn about promises, there are many examples online but what I really liked is the promise tutorial at google , with this nice snippet that explains it要了解 promises,网上有很多例子,但我真正喜欢的是googlepromise 教程,这个很好的片段解释了它

var promise = new Promise(function(resolve, reject) {
  // do a thing, possibly async, then…

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

then, once you have the function that returns this promise, you can start doing然后,一旦你有了返回这个承诺的函数,你就可以开始做

.then(...)
.then(...)
.then(...)
.catch(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM