const poll = require('./poll')

function pollify(script, context, key) {
  return options =>
    function () {
      if (!context[key]) {
        context[key] = {}
        Promise.resolve()
          .then(() => script.apply(null, arguments))
          .then(value => (context[key].value = value))
          .catch(err => (context[key].error = err.message))
      }
      return poll(context, key, options)
    }
}

module.exports = pollify
