【问题标题】:Conditionally chaining promises not working有条件地链接承诺不起作用
【发布时间】:2019-11-19 00:18:03
【问题描述】:

我正在使用带有 Typescript 的 React 并具有此功能:

const saveData = (): Promise<any> => {
        const promise = new Promise((s:any,f:any) => s(true))

        if (true) {
            promise.then(() => 5)
        }

        return promise
}

然后我将它作为处理程序道具传递给某个组件:

<Component save={() => {saveData().then(a => console.log)}}

这总是记录 true 而应该记录 5,为什么?我如何有效地链接这些承诺。我在这里做错了什么?

这是一个codesandbox.io的例子:

https://codesandbox.io/embed/practical-montalcini-5njyg

【问题讨论】:

  • 试试return promise.then(...)
  • 不起作用,console.log 中仍然出现true

标签: reactjs typescript promise es6-promise


【解决方案1】:

then 不会更改调用它的承诺,它会返回一个您忽略的新承诺。要么存回promise,要么直接退回

const saveData = (): Promise<any> => {
        const promise = new Promise((s:any,f:any) => s(true))

        if (true as boolean) { // as boolean to make ts not complain about unreachable code
            return promise.then(() => 5)
        }

        return promise
}

还可以考虑将 async/await 与 Promise 一起使用,以获得更好的编码体验:

const saveData = async (): Promise<any> => {
        await Promise.resolve();

        if (Math.random() > 0.5) {
            return 5
        }
        return 0;
}

【讨论】:

    猜你喜欢
    • 2016-01-07
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2017-11-23
    • 1970-01-01
    相关资源
    最近更新 更多