简体   繁体   English

递归异步函数中的承诺

[英]Promises in recursive asynchronous functions

I want to take a chrome bookmark and find its parents, all the way up to the parent bookmark folder. 我想要一个chrome书签并找到其父级,一直到父级书签文件夹。

The function below works for getting the first parent of the given bookmark. 下面的函数用于获取给定书签的第一个父对象。

function getParent(bookmark) {
  var promise = new Promise(function(resolve, reject) {
    chrome.bookmarks.get(bookmark.parentId, function(nodes) {
      resolve(nodes[0]);
    });
  });
  return promise;
}

I'm having trouble getting all of the bookmarks parents. 我在让所有书签的父母都遇到麻烦。 The function below doesn't work but it should show what I'm looking for. 下面的功能不起作用,但它应该显示我在寻找什么。

function getParents(bookmark, parents) {
  var parents = parents || [];
  var promise;

  getParent(bookmark).then(function(parent) {
    if (parent.parentId == '0') {
      parents.push(parent);
      promise = Promise.resolve(parents);
    } else {
      parents.push(parent);
      getParents(parent, parents);
    }
  });
  return promise;
}

I guess my real question is: how do you get promises to work in recursive asynchronous functions? 我想我的真正问题是:如何获得在递归异步函数中工作的承诺?

Or if you have a better way of doing this, that works too. 或者,如果您有更好的方法可以这样做,也可以。

Simply return the promise returned by .then and either return the final value from the .then callback, or another promise: 只需返回.then返回的promise .then然后从.then回调中返回最终值,或返回另一个promise:

function getParents(bookmark, parents) {
  var parents = parents || [];

  return getParent(bookmark).then(function(parent) {
    parents.push(parent);
    return parent.parentId == '0' ? parents : getParents(parent, parents);
  });
}

See http://www.html5rocks.com/en/tutorials/es6/promises/#toc-chaining 请参阅http://www.html5rocks.com/zh-CN/tutorials/es6/promises/#toc-chaining

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

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