Promise topic 02 - promise result, basic process of promise, promise API (constructor, then, catch, resolve, reject, all, race), several key issues

1. promise object value promiseResult

A property in promise object: [promiseResult]
Save the results of the success or failure of the object
This value is manipulated by the resolve and reject functions

if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              resolve(xhr.response)
            } else {
              reject(xhr.status)
            }
          }

The above code is the value of resolve and reject in operating this promiseResult

2. Basic process of promis

3. Use of promise

1. Constructor of promise: Promise (excutor) {}

2,Promise.prototype.then: (onResolved´╝îonRejected){}

3,Promise.prototype.catch: (onRejected)=>{}
Only failed callback functions can be specified

4. Promise.resolve method: (value) = > {}
value: successful data or promise object
Description: returns a success / failure promise object

let promise1=Promise.resolve('Successfully implemented promise')
    //If the passed in parameter is an object of non promise type, the returned result is a successful promise object
    console.log(promise1)//Print successfully executed promise
    //If the passed in parameter is a promise object, the result of the parameter determines the result of resolve
    let promise2=Promise.resolve(new Promise((resolve,reject )=>{
      resolve('success')
    }))
    console.log(promise2)//Printing succeeded

5. Promise.reject method: (reason) = > {}
Reason: reason for failure
Description: returns a failed promise object

<script>

  $('#send_ajax').click(function(){
    let promise1=Promise.reject('Failed to execute promise')
    //If the passed in parameter is an object of non promise type, the returned result is a successful promise object
    console.log('promise1',promise1)//Print failed to execute promise
    //If the passed in parameter is a promise object, the result of the parameter determines the result of resolve
    let promise2=Promise.reject(new Promise((resolve,reject )=>{
      reject('fail')
    }))
    console.log('promise2',promise2)//Printing succeeded
    promise1.catch((reason)=>{
      console.log('promise1',reason)
    })
    promise2.catch((reason)=>{
      console.log('promise2',reason)
    })
    let promise3=Promise.reject(new Promise((resolve,reject )=>{
      resolve('success')
    }))
    console.log('promise3',promise3)//The successful promise passed in in time also failed in the end
    promise3.catch((reason)=>{
      console.log('promise3',reason)
    })
  })
</script>

6. Promise.all method: (promises) = > {}
promises: an array containing n promise s
Note: a new promise is returned. It will succeed only if all promises are successful. As long as one fails, it will fail directly

  • If both are successful, the returned result is an array of successful result values
  • If one fails, the value of the promise that failed is returned
<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('p1 success')
    })

    const p2=new Promise((resolve,reject)=>{
      resolve('p2 ok')
    })

    const p3=new Promise((resolve,reject)=>{
      resolve('p3 success')
    })

    const resualt=Promise.all([p1,p2,p3])
    console.log(resualt)

  })
</script>


If one fails

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('p1 success')
    })

    const p2=new Promise((resolve,reject)=>{
      reject('p2 fail')
    })

    const p3=new Promise((resolve,reject)=>{
      resolve('p3 success')
    })

    const resualt=Promise.all([p1,p2,p3])
    console.log(resualt)

    p2.catch((err)=>{
      console.log('p2==='+err)
    })
    resualt.catch((err)=>{
      console.log('p**resualt==='+err)
    })

  })
</script>


If there is more than one reject, the result of the first reject will be displayed. It may be that if the first reject is found, it will not be calculated down

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      reject('p1 fail')
    })

    const p2=new Promise((resolve,reject)=>{
      reject('p2 fail')
    })

    const p3=new Promise((resolve,reject)=>{
      resolve('p3 success')
    })

    const resualt=Promise.all([p1,p2,p3])
    console.log(resualt)

    p1.catch((err)=>{
      console.log('p1==='+err)
    })

    p2.catch((err)=>{
      console.log('p2==='+err)
    })
    resualt.catch((err)=>{
      console.log('p**resualt==='+err)
    })

  })
</script>

7. Promise.race method: (promises) = > {}
promises is an array containing n promise s
Note: a new promise is returned. The result state of the first completed promise is the final result state

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('p1 success')
    })

    const p2=new Promise((resolve,reject)=>{
      reject('p2 fail')
    })

    const p3=new Promise((resolve,reject)=>{
      resolve('p3 success')
    })

    const resualt=Promise.race([p1,p2,p3])
    console.log(resualt)


  })
</script>

4. Some key problems of promise

1. How does the promise state change
promise status is pending
Change the use of resolve to full, that is, success
Use reject to change to reject
The use of throw can also be changed to reject

2. A promise specifies multiple success / failure callback functions. Will they be called
Called when promise changes to the corresponding state

3. Change the promise state and specify who comes first and who comes later in the callback function
1. It is possible to specify the callback first and then change the state, but it is also possible to change the state first and then specify the callback
2. How to change status before specifying callback
a. Directly call resolve() / reject() / / in the executor, and synchronize the task in the resolve() / / remove. This line changes the state

<script>
  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('p1 success')//Change the state first
    })

    p1.then(value=>{ //Then specify the callback
      console.log(value)
    })
  })
</script>
b,Delay longer to call then()//Generally, asynchronous operations such as settimeout or time-consuming operations are used
<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      setTimeout(()=>{
        resolve('success')
      },1000)
    })

    p1.then(value=>{ //Then specify the callback
      console.log(value)
    })
  })
</script>

3. When can I get the data (when the callback function is declared)
a. If the callback is specified first, when the state changes, the callback function will be called to get the data
b. If you change the state first, when the callback is specified, the function will be called to get the data.

3. The result status of the new promise returned by promise.then() is determined by the declaration
a. Determined by the execution result of the callback function specified by then()
b-1: if an exception is thrown, the new promise becomes rejected, and reason is the exception thrown

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      throw 'Error '
    })

    const result=p1.then(value=>{ //Then specify the callback
      console.log(value)
    })

    console.log(result)

  })
</script>

b-2: if any value other than promise is returned, the new promise becomes resolve and value is the return value

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('success')
    })

    const result=p1.then(value=>{ //Then specify the callback
      return 'Returns a non promise content'
    })

    console.log(result)//The value of result is the result returned in then

  })
</script>

b-3: if another new promise is returned, the result of this promise will become the result of the new promise

<script>

  $('#send_ajax').click(function(){
    const p1=new Promise((resolve,reject)=>{
      resolve('success')
    })

    const result=p1.then(value=>{ //Then specify the callback
      return p2=new Promise((resolve,reject)=>{
        resolve('ok')
      })
    })

    console.log(result)//The value of result is the result returned in then
    result.then((value)=>{
      console.log('the previous promise The returned value is'+value)
    },()=>{})

  })
</script>


The chained call then () foreshadows

Keywords: Javascript Promise

Added by vahidf on Fri, 15 Oct 2021 01:16:44 +0300