【问题标题】:Passing a generator as callback in javascript在javascript中将生成器作为回调传递
【发布时间】:2019-12-19 03:22:29
【问题描述】:

在我的 redux-saga 函数中,我需要在回调中产生一个 put。所以我将生成器作为回调传递。但是我的回调没有执行。相反,如果我使用匿名函数,那么回调就会运行。

这会记录数据:

  Tabletop.init({
    key: action.key,
    callback: googleData => {
      console.log(googleData);
    },
    simpleSheet: true
  });

这不会记录数据:

  Tabletop.init({
    key: action.key,
    callback: yield function*(googleData) {
      console.log(googleData);
      yield put(setProblems(googleData));
    },
    simpleSheet: true
  });

我在网上看到你可以在承诺的一部分中让步。 Tabletop.js 支持这样的 Promise:

function init() {
  Tabletop.init( {
    key: 'https://docs.google.com/spreadsheets/d/0AmYzu_s7QHsmdDNZUzRlYldnWTZCLXdrMXlYQzVxSFE/pubhtml',
    simpleSheet: true }
  ).then(function(data, tabletop) { 
    console.log(data)
  })
}

但是当我收到此错误时,这种方式对我不起作用:

TypeError: undefined is not a function (near '...}).then(function (data, tab...')

[https://github.com/jsoma/tabletop/issues/175]

有人能告诉我让它工作的正确方法吗?获取数据后,我想将其设置在减速器中。

【问题讨论】:

  • 你使用的是什么版本的Tabletop
  • 我使用的是 1.5.2。我想这就是问题所在。

标签: javascript redux generator es6-promise redux-saga


【解决方案1】:

所以这就是我让它工作的方式。如果有任何其他方法可以使这项工作,请告诉我。

我创建了一个返回承诺的函数:

function fetchProblemsPromise(key) {
  return new Promise(resolve => {
    Tabletop.init({
      key: key,
      callback: googleData => {
        resolve(googleData);
      },
      simpleSheet: true
    });
  });
}

然后屈服了:

const data = yield call(fetchProblemsPromise, [action.key]);
yield put(setProblems(data));

这帮助我弄清楚了:
https://github.com/redux-saga/redux-saga/issues/508

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多