How do promises work in JavaScript?

前端 未结 4 552
时光取名叫无心
时光取名叫无心 2020-11-28 09:06

I just implemented my first function that returns a promise based on another promise in AngularJS, and it worked. But before I decided to just do it, I spent 2 hour

4条回答
  •  半阙折子戏
    2020-11-28 09:11

    please check this simple promise code. this will help you to better understand of promise functionality.

    A promise is an object that may produce a single value some time in the future: either a resolved value, or a reason that it’s not resolved. A promise may be in one of 3 possible states: fulfilled, rejected, or pending. Promise users can attach callbacks to handle the fulfilled value or the reason for rejection.

    let myPromise = new Promise((resolve, reject)=>{
      if(2==2){
        resolve("resolved")
      }else{
        reject("rejected")
      }
    });
    
    myPromise.then((message)=>{
      document.write(`the promise is ${message}`)
    }).catch((message)=>{
      document.write(`the promise is ${message}`)
    })

    check this out

提交回复
热议问题