Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - When or who does pass resolve and reject functions to JS promises?

I have begin learning javascript promises. But I just can't understand the concept of promises. The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

See this example of Promise:

function getImage(url){
    return new Promise(function(resolve, reject){
        var img = new Image()
        img.onload = function(){
            resolve(url)
        }
        img.onerror = function(){
            reject(url)
        }
        img.src = url
    })
}

Now who does pass resolve and reject methods , as my understanding of javascript says me that this script will throw unknown variable errors as resolve and rejects are not defined ?

getImage('doggy.jpg').then(function(successurl){
    document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />'
}).catch(function(errorurl){
    console.log('Error loading ' + errorurl)
})

Now you see a method like the above , the only way these methods(resolve and reject) are passed are via then and catch as used in above method call to getImage.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The thing that bothers me most is who is passing the Resolver and Reject function to a promise constructor ?

Nobody.

The functions are passed by the promise constructor.

They are passed to the function which you pass as the first argument to the promise constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...