📜  承诺链 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:08.794000             🧑  作者: Mango

代码示例1
/* Let's break n STEP-BY-STEP (cpy paste n console u'll have clear view)

1. Promises chaining will allow us to add many async operations
 in a sequence way (i.e  in order)
2. But like we have callback hell, here our code at the end 
will be more difficult to read
3. TIPS : Best options are go with >> {FETCH API, Async/Await} 
4. NOTE : Learn promises once, understand no.3 in a easy way, above
both completely relay on Promises concept, makesure u understand them
clearly. */


//EXAMPLE

var result = true;
var learsJS = new Promise((resolve,reject) => {
  setTimeout(() => {
    if(result){ //if true resolve below case
    resolve("This is my 1st resolved case");
  }
    else{
    reject("I need some more time");
  }
  }, 2000);
}).then(resolvedData1 => {
    console.log(resolvedData1); //resolved promise1 - 5th line
  return new Promise((resolve) => { // returning another promise2
    resolve(`${resolvedData1} -- This is 2nd resolved case`)
  });
})
.then(resolvedData2 => {
  console.log(resolvedData2); //resolved promise2
    return new Promise((resolve) => { // returning another promise3
    resolve(` ${resolvedData2} -- This is my 3rd resolved case`)
  })
})
.then(resolvedData3 => {
  console.log(resolvedData3); //resolved promise3
    return new Promise((resolve) => { //returning final promise
    resolve(` ${resolvedData3} -- This is my Final resolved case`)
  })
})
.then(finalData => console.log(finalData)); //resolved final promise