使用 bluebird 从 JSON 建立承诺

Build promises from JSON with bluebird

我有一个 uniq 问题。我有 JSON 代表生成承诺的步骤的数据。

[
  {
     action: 'wait' 
  },
  {
     action: 'screenshot' 
  }
]

现在我正在用 Bluebird 生成这个承诺。

var pr = require('bluebird/js/main/promise')();
var R = require('bluebird');

var Worker = {
  open: function () {
    return new pr(function (resolve, reject) {
      resolve('opened');
    });
  },
  wait: function (milliseconds) {
    return pr.delay(milliseconds);
  },

  screenshot: function (milliseconds) {
    return new pr(function (resolve, reject) {
      resolve('take screenshot');
    });
  }
}

var defers = [];
Worker.open();
JSON.forEach(function (vl) {
  var defer = R.defer();
  defers.push(defer.promise);
  Worker[vl.action]().then(function () {
    // do something
    defer.resolve();
  });
});
R.all(defers).then(function () { console.log('finished');});

现在这行不通了,因为 promises 没有被链接起来。有人建议我将它们链接起来。

 var pr = require('bluebird/js/main/promise')();
var R = require('bluebird');

var Worker = {
  open: function () {
    return new pr(function (resolve, reject) {
      resolve('opened');
    });
  },
  wait: function (milliseconds) {
    return pr.delay(milliseconds);
  },

  screenshot: function (milliseconds) {
    return new pr(function (resolve, reject) {
      resolve('take screenshot');
    });
  }
}

var defers = [];
var chain = Worker.open();
JSON.forEach(function (vl) {
  var defer = R.defer();
  defers.push(defer.promise);
  chain = chain[vl.action]().then(function () {
    // do something
    defer.resolve();
  });
});
R.all(defers).then(function () { console.log('finished')});

但这也行不通,关于如何从 JSON 数据生成基于承诺的函数有什么建议吗?

我认为您对链接承诺有点困惑。

您需要在上一个动作的承诺.then(...)中进行下一个动作。

var chain = Worker.open();
JSON.forEach(function (vl) {
    chain = chain.then(function () {
        //You need to return to promise from Worker[vl.action]() to correctly chain actions
        return Worker[vl.action]();
    });
    //"chain" is now synchronized with the promise of the last chained action
});

您想获取操作数组,然后将其缩减为单个 Promise 值。

const actions = [
  {action: 'wait'},
  {action: 'screenshot'}
];

const allDone = actions.reduce((promise, item) => 
  promise.then(Worker[item.action]), Promise.resolve());

allDone.then(() => console.log("All done!"));

这表示:"Reduce the array by chaining the item's action onto the promise with .then(), starting from an empty Promise."


应要求,ES5(学习ES2015,太棒了!)

var actions = [
  {action: 'wait'},
  {action: 'screenshot'}
];

var allDone = actions.reduce(function(promise, item) {
  return promise.then(Worker[item.action])
}, Promise.resolve());

allDone.then(function() { 
  console.log("All done!"); 
});