【问题标题】:how to check for a condition in the .then() function of the Promise [duplicate]如何检查 Promise 的 .then() 函数中的条件 [重复]
【发布时间】:2019-02-27 08:18:35
【问题描述】:

我正在尝试检查 api 调用的结果是否返回任何内容并在此基础上执行一些其他操作,但以下代码始终通过 process_result() 函数,即使结果是空对象,任何人都可以看到我做错了什么,

RemoteApi.api_request(server, method, url, data)
    .then(result => {
        debug("result from API request: ", result)
        debug("data from API request: ", data)
        if (result !== {}) {
            debug("in process result now")
            process_result(result, label, model, dispatchOptions)
                .then(body => {
                    onSuccess(body)
                })
                .catch(error => {
                    onFailure(error)
                })
        } else {
            debug("outside process result now")
        }
    })
    .catch(error => onFailure(error))

【问题讨论】:

  • 你需要一个不同的检查; 每个对象,无论是哪种类型,都将是!== {}(与那个新对象不同)。
  • if (result)

标签: javascript reactjs ecmascript-6 ecmascript-5


【解决方案1】:

通常返回 2XX 结果的远程请求将进入您的then() 函数。在那里,它是普通的旧 JavaScript。

如果你想确保结果是一个对象,你可以检查类型:

if (typeof result === 'object') {
  // success
}

如果你不关心结果内容但你想检查数据是否存在,你可以检查它是否真实:

if (result) {
  // success
}

远程结果永远不会是 {} 的相同实例,因此您的结果过程将始终是真实的。

【讨论】:

    猜你喜欢
    • 2018-06-12
    • 1970-01-01
    • 2018-09-21
    • 2016-09-25
    • 2015-03-17
    • 1970-01-01
    • 2021-05-29
    • 2017-07-21
    • 2020-11-29
    相关资源
    最近更新 更多