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

后端 未结 5 1616
无人共我
无人共我 2021-01-12 11:52

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 fun

5条回答
  •  情话喂你
    2021-01-12 12:27

    I had the same problem in understanding Promises.You need to look at the process of promise creation carefully. when you write var promise= new Promise(function(resolve,reject){...})

    you are actually invoking constructor of Promise class or creating an object of Promise class. Now Promise constructor requires a function callback. Now resolve and reject are just function arguments and not any other values. You can write anything in place of resolve or reject like resolveHandler or rejectHandler.

    These resolve or reject are nothing but the function callback that Promise calls when Promise is executed.

    Now resolve is called when Promise is executed successfully and reject is called when promise is executed with some error or unsuccessfully .

    The argument with which resolve is called can be accessed inside then like this

    getImage().then(function(valueSentInResolve){ console.log('')})
    

    The argument with which reject is called can be accessed inside catch like this

    getImage().then(function(valueSentInResolve)
      {//..do something}
    ).catch(function(errorSentInReject){
      console.log('error',errorSentInReject )
    })
    

    I hope that helps.Let me know if I said anything wrong.

提交回复
热议问题