Promise () related learning

1. What is Promise?

  • Mainly used for asynchronous computing
  • Asynchronous operations can be queued, executed in the desired order, and return the expected results
  • Promises can be passed and manipulated between objects to help us handle queues

2. Promise benefits

  • Promise is an object. The difference between an object and a function is that an object can save state, but a function cannot (except for closures)
  • It can solve the problem of callback abyss very well
  • The syntax is concise. Readable
  • Multiple asynchronous await merges for easy resolution

3. Usage

  • resolve: Change the state of the Promise object from "unfulfilled" to "successful" (that is, from pending to fulfilled). Change the asynchronous execution from pending (request) to resolve (successful return), which is a function execution return.
  • reject: Change the state of the Promise object from "unfulfilled" to "failed" (that is, from pending to rejected). As the name implies, "rejection" means that the request has changed to "failure". It is a function that can be executed and returns a result, but we recommend that you return an error new Error(), or return a string directly.
  • The instance constructed by Promise has then(), catch(), finally() methods
  • There are only two possibilities for the state of Promise to change: from pending to fulfilled; from pending to rejected.
const function1 = new Promise((resolve, reject) => {
    
    
    // resolve('what do you do?')
    reject(new Error('find problem?'))
})
function1
    .then(res => {
    
    
      console.log(res)
    })
    .catch(err => {
    
    
      console.log(err)
    })

4. use

(1) If there are two asynchronous operations (execution takes time), eating and collecting bowls are function1() and function2() respectively, setTimeout() simulates the time required, and requires the two asynchronous operations to be executed in order, first function1() then execute function2()
const fun1 = () => {
    
    
  // 模拟接口返回时间
  setTimeout(() => {
    
    
   	console.log('吃饭')
  }, 200)
}
const fun2 = () => {
    
    
  setTimeout(() => {
    
    
    console.log('收碗')
  },100)
}
fun1()
fun2()

// 执行结果:
//收碗
//吃饭

In this way of writing, the execution of the two functions is synchronized and carried out at the same time, which is obviously not the result we want

const fun1 = new Promise((resolve, reject) => {
    
    
  setTimeout(() => {
    
    
    resolve('吃饭')
    // reject(new Error('find problem?'))
  }, 200)
})
const fun2 = () => {
    
    
  setTimeout(() => {
    
    
    console.log('收碗')
  },100)
}
fun1
  .then(res => {
    
    
    console.log(res)
    fun2()
  })
  .catch(err => {
    
    
    console.log(err)
  })

// 执行结果:
//吃饭
//收碗

fun1 () constructs an instance with Promise and returns it with resolve, then () method receives the data passed by resolve. In this way, wait until fun1() is executed before executing fun2().

(2) Solve the hell callback, change the code method of function nesting to the same level, and support chain call
const fun1 = f => {
    
    
  console.log('f1')
  f()
}
const fun2 = f => {
    
    
  console.log('f2')
  f()
}
const fun3 = f => {
    
    
  console.log('f3')
  f()
}
const fun4 = f => {
    
    
  console.log('f4')
  f()
}
fun1(() => {
    
    
  fun2(() => {
    
    
    fun3(() => {
    
    
      fun4(() => {
    
    })
    })
  })
})

//输出结果
//f1
//f2
//f3
//f4

Function nesting, layer by layer, hell callback

const fun1 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    resolve('f1')
  })
}
const fun2 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    resolve('f2')
  })
}
const fun3 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    resolve('f3')
  })
}
const fun4 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    resolve('f4')
  })
}
fun1()
  .then(res => {
    
    
    console.log(res)
    return fun2()
  })
  .then(res => {
    
    
    console.log(res)
    return fun3()
  })
  .then(res => {
    
    
    console.log(res)
    return fun4()
  })
  .then(res => {
    
    
    console.log(res)
  })

Using Promise () can be changed to a flat level to solve the hell callback. It can also be solved by async+await

5. Usage of all() and race()

  • The Promise.all() method provides the ability to execute asynchronous operations in parallel, and the then() callback is executed after all asynchronous operations are executed, and catch() is executed when one fails.
const fun1 = new Promise((resolve, reject) => {
    
    
  resolve('f1')
})
const fun2 = new Promise((resolve, reject) => {
    
    
  resolve('f2')
  // reject('f2 error')
})
const fun3 = new Promise((resolve, reject) => {
    
    
  resolve('f3')
})
const fun = () => {
    
    
  return Promise.all([fun1, fun2, fun3])
}
fun()
  .then(res => {
    
    
    const [fun1, fun2, fun3] = res
    console.log(fun1, fun2, fun3)
  })
  .catch(err => {
    
    
    console.log(err)
  })

// 输出结果:
//f1,f2,f3
//若fun2改为reject('f2 error')
//则结果:
//f2 error
  • Promise.race(), whichever result is obtained quickly, returns that result, regardless of whether the result itself is a success state or a failure state
const fun1 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve('f1')
    }, 300)
  })
}
const fun2 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      // resolve('f2')
      reject('f2 error')
    })
  }, 100)
}
const fun3 = () => {
    
    
  return new Promise((resolve, reject) => {
    
    
    setTimeout(() => {
    
    
      resolve('f3')
    }, 200)
  })
}
const fun = () => {
    
    
  return Promise.race([fun1(), fun2(), fun3()])
}
fun()
  .then(res => {
    
    
    console.log(res)
  })
  .catch(err => {
    
    
    console.log(err)
 })
 //输出结果:
 //f2 error

6. resolve() and reject() can be called directly

  • Promise.resolve() and Promise.reject() can be called directly. Sometimes, when it is judged that the promise does not need to be executed, we don't need to use new to create the Promise object, but can directly call Promise.resolve() and Promise.reject().
const fun1 = () => {
    
    
  return Promise.resolve('f1')
}
const fun2 = () => {
    
    
  return Promise.reject('f2 error')
}
fun1().then(res => {
    
    
  console.log(res)
})
fun2().catch(err => {
    
    
  console.log(err)
})
//输出结果
//f1
//f2 error

Guess you like

Origin blog.csdn.net/qq_45616003/article/details/124839393