【问题标题】:What is the main difference between Closure,Callback,Promise in JavaScript and How all are they Unique?JavaScript 中的 Closure、Callback、Promise 和它们之间的主要区别是什么?
【发布时间】:2019-05-09 02:23:52
【问题描述】:

(我是JavaScript初学者,对javascript理解有疑问)

我的函数有什么作用?

使用axios通过三种方式从api获取请求和响应并记录状态

这在三个变体中实现(回调、关闭、承诺)

我的理解:

易读性和可读性按以下顺序更好:

承诺 > 闭包 > 回调

//Callback

onMakeApiCallback() {
    this.getData((response) => {
        console.log("data callback success", response)
    }, (error) => {
        console.log("error is", error)
    })
}

getData(onApiSuccess, onApiFail) {
    axios.get("https://rallycoding.herokuapp.com/api/music_albums")
        .then(function(response,error) {
            if(response.data[3].title === "Red") {
                onApiSuccess(response)
            } else {
                onApiFail(error)
            }
        })
}

以上是使用回调完成的,我将一个函数作为参数发送给另一个函数。与其他两种方法相比,我发现这种方法很复杂。

//Closure

onMakeApiClosure() {
    axios.get("https://rallycoding.herokuapp.com/api/music_albums")
        .then(function(response,error) {
            function innerfunction(response,error) {
                if(response) {
                    console.log("success")
                } else {
                    console.log("fail",error)
                }
            }
            return innerfunction(response,error)
        })
}

以上是在函数中使用 Closure.Function 完成的

// Promise

onMakeApiPromise() {
    axios.get('https://rallycoding.herokuapp.com/api/music_albums')                 
        .then(function(response,error) {
            console.log("1", response.data[3].title)
            if(response.data[3].title === "Red") {
                console.log("data is success", response)
            } else if(error) {
                console.log("error is ", error)
            } else {
                console.log("not equal")
            }
        })   
}
  1. 什么时候用什么?
  2. 这三者之间是否存在与性能或任何其他特征相关的其他差异?

【问题讨论】:

标签: javascript callback promise closures


【解决方案1】:

了解的链接

【讨论】:

    猜你喜欢
    • 2018-11-10
    • 2012-03-20
    • 2015-08-22
    • 2015-08-06
    • 2011-03-06
    • 2013-12-23
    • 2017-04-28
    • 2011-04-14
    • 2010-09-17
    相关资源
    最近更新 更多