簡體   English   中英

如何在 JavaScript 中使用多個子異步請求鏈接承諾?

[英]How to chain promises with several child asynchronous request in JavaScript?

我有幾個異步函數,我希望它們都同步運行。 所以嘗試使用 Promise 來做,但它沒有等待第三個 function 完成。 它在 asyncDataRequestOne 請求后返回循環。

我進行了搜索,但找不到如下或類似鏈接承諾的示例。

這是我嘗試過的

試驗 1


function three(j){
 return new Promise((resolve,reject)=>{
   asyncDataRequestThree(()=>{
     let k = j + 14; 
     resolve();
   });
 });
}

function two(i){
 return new Promise((resolve, reject)=>{
  asyncDataRequestOne().then(()=>{
   asyncDataRequestTwo().then(()=>{
     let  = i+ 7;
     three(j);
     resolve()
   });
  });
 });
}

function one(){
  //Each loop should run only after function three's resolve
  arr.forEach((i) => {
    two(i);
  }
}

試驗 2

function async three(j){
   await asyncDataRequestThree(()=>{
     let k = j + 14; 
   });
 });
}

function async two(i){
  await asyncDataRequestOne().then(  async ()=>{
   await asyncDataRequestTwo().then(  async ()=>{
     let  = i+ 7;
     await three(j);
   });
  });
}

function one(){
  //Each loop should run only after function three's resolve
  arr.forEach( async () =>{
    await two(i);
  }
}

謝謝

Array 的forEach循環在內部實現了如下內容:

for (var element in array) {
  callback(element); // assuming callback is the argument of Array.forEach()
}

因此,如果您將async添加到 function 聲明中,它只會使其返回Promise 循環不會等待callbackPromise完成,它只會等待callback本身完成。 否則Array.forEach()也必須返回Promise

// assuming asyncDataRequestOne, asyncDataRequestTwo, asyncDataRequestThree will return Promise
async three(j) {
  await asyncDataRequestThree();
  // some kind of operation with j
}

async two(i) {
  await asyncDataRequestOne();
  await asyncDataRequestTwo();
  let j = i + 7;
  await three(j)
}

async function one() {
   for (let i = 0; i < 10; i++) {
      await two(i);
   }
}

your two function will be resolved and returns a promise to your loop hence why i will break the chain and it won't await for your three function to resolve which means if you want your three function to return promise before the next loop one of the可能性是不要在你的兩個 function 中使用 promise

 function three(p){ return new Promise((resolve,reject)=>{ k = p + 14,resolve(console.log(k)) }) } function two(i){ return j = i+ 7,three(j) } i=0 function one(){ //Each loop should run only after function three's resolve while(i < 10){ two(i) i++ } } one()

或使用異步等待,您的代碼應如下所示

 var promise3=function three(p){ return new Promise((resolve,reject)=>{ k = p + 14,resolve(console.log(k)) }) } var promise2=function two(i){ return new Promise((resolve, reject)=>{ let j = i+ 7; resolve(j) }) } i=0 async function one(){ //Each loop should run only after function three's resolve while(i < 10){ r1= await promise2(i) r2= await(promise3(r1)) i++ } } one()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM