2017-10-06 72 views
1

我有這個。用超時解決承諾鏈。 Promise.all

const getPrice = function(database){ 
    return new Promise(function (resolve, reject){ 
     var promises =[]; 
     for(var i in database){ 
      promises.push(Update.requestClassifieds(database[i])) 
     } 
    Promise.all(promises) 
     .then(function(todos){ 
      return resolve(todos); 
     }) 
})} 

Update.prototype.requestClassifieds = function(item){ 
    var ithis = this; 
    return new Promise((resolve, reject) => { 
     var input = {}; 
     request({ 
      url: '', 
      method: "GET", 
      json: true, 
      body: input 
    }, function (error, response, body){ 
    if (error){ 
     return resolve(item); 
    } 
    else if(body){ 
     return resolve(item); 
    } 
    } 
}); 
}); 
} 

我需要爲數據庫中的每個項目請求數據。所以,我爲此創造了一系列承諾。

我正在請求一個有5秒冷卻時間的api數據。所以,我需要等待5秒,直到解決下一個承諾Promise.all(承諾)

如何在Promise.all中的每個承諾之間設置TimeTimeout?

+0

這是一個壞主意,有一個問題,爲什麼你需要之間的5秒倒計時承諾?有關數據庫訪問的任何事 – Kalamarico

+0

@Kalamarico我使用的Api有5秒的冷卻時間。 –

回答

0

你需要在你的循環

const getPrice = function (database) { 
    var promisesChain = Promise.resolve(); // Promise chain 
    var todos = []; // results to be stored 
    for (var i in database) { 
     promisesChain = promisesChain.then(((i) =>() => { // create closure to grab database[i] 
      return Update.requestClassifieds(database[i]) 
     })(i)).then((res) => { 
      return new Promise((resolve, reject) => { 
       setTimeout(() => { // store result of requestClassifieds and resolve after 5sec 
        todos.push(res); 
        resolve(); 
       }, 500); 
      }); 
     }) 
    } 
    return promisesChain.then(() => {return todos}); 
}; 

運行例如創建Promise

const getPrice = function (database) { 
 
\t var promisesChain = Promise.resolve(); 
 
\t var todos = []; 
 
\t for (var i in database) { 
 
\t \t promisesChain = promisesChain.then(((i) =>() => { 
 
\t \t \t return Update.requestClassifieds(database[i]) 
 
\t \t })(i)).then((res) => { 
 
\t \t \t return new Promise((resolve, reject) => { 
 
\t \t \t \t setTimeout(() => { 
 
\t \t \t \t \t todos.push(res); 
 
\t \t \t \t \t resolve(); 
 
      console.log('resolve', res); 
 
\t \t \t \t }, 1000); 
 
\t \t \t }); 
 
\t \t }) 
 
\t } 
 
\t return promisesChain.then(() => {return todos}); 
 
}; 
 
const Update = {}; 
 
Update.requestClassifieds = function (i) { 
 
\t console.log('got', i); 
 
\t return new Promise((resolve, reject) => { 
 
\t \t resolve(i) 
 
\t }); 
 
} 
 
getPrice({ 
 
\t a: 'A', 
 
\t b : 'B', 
 
\t c : 'C' 
 
}).then(console.log);

+0

我認爲這是最好的解決方案。一個問題:如果我想讓getPrice將結果作爲數組返回,因爲我想使用它們。 (function(){console.log(todos); //顯示結果 })「 –

+0

更改'promisesChain.then(function(){console.log(todos); (顯示結果})'到'promisesChain.then(()=> {return todos});'so'getPrice'將返回'Promise',用結果數組解析 –

+0

@TomasGonzalez看看更新後的答案 –