Redux Saga:等待承诺

Redux Saga: Await Promise

我有一个已经调用的承诺,必须等待。基本上:

const foo = () => Promise.resolve('foo'); // The real promise takes time to resolve.

const result = foo();

await result; // This line has to happen in the saga

如何等待未决的承诺?如果我将它包装在 call Redux Saga 尝试调用它并崩溃。

const myFunc = async () => {
  const result = await foo();
  return result;
  // or just return foo() without await, as it is last statememnt in async func
}

否则你总是可以做

foo()
  .then((result) => console.log('result', result))
  .catch((err) => console.error(err));

如果您身处传奇,只需 yield 承诺即可。 Redux saga 将等待它解决然后恢复 saga,就像 awaitasync 函数中所做的那样:

const foo = () => Promise.resolve('foo');
const resultingPromise = foo();

function* exampleSaga() {
  const result = yield resultingPromise;
  console.log(result); // 'foo'
}

如果 promise 可能会被拒绝,您可以将其包装在 try catch 中:

try {
  const result = yield resultingPromise;
  console.log(result);
} catch(err) {
  console.log('promise rejected', err);
}