[英]How do I make this async foreach loop work with promises?
我已經把Promise搞砸了,但是我對他們很陌生,我無法弄清楚如何正確地做到這一點。 目前,Promise沒有任何意義,因為它不會等到async $.get
完成。
基本上,每個foreach
迭代都有自己的$.get
函數,我需要將它們全部完成,然后繼續使用具有“... gets albumart” console.log
。
$.get(id,function(data) {
//(there's some code here)
var getZippyUrls = new Promise(function(resolve) {
zippyarray.forEach(function(zippy) {
//(more code)
$.get(zippy.full, function(data) {
//^This is the foreach of $.gets
//(code's here)
});
resolve(zippyarray);
});
});
//This is my failed Promise ->
getZippyUrls.then(function(response) {
console.log("WE'RE OUT " + response.length);
response.foreach(function(d) {
console.log("Promise"+d.media);
});
console.log('eyyyyyy');
});
console.log("...gets albumart");
//Now after the previous stuff is done, move on
在同步代碼中,當行結束時執行繼續;
通過承諾,繼續通過.then
執行。 您正在使用promise構造函數並立即解決它,您根本沒有等待任何任務。 我將我的工作映射到任務中,然后用它們鏈接它們或者連續等待它們。
//I'm assuming
zippyarray; // array of Zippy objects
var tasks = zippyarray.map(function(zippy,i){
return function(){ // return a task on that zippy;
// basic logic here
return $.get({
// ajax request
}).then(function(data){
// process data like in your code
// possibly store later for later use too
return process(data); // return the processed data;
});
}
});
現在我們可以按順序執行它們:
var p = tasks[0](); // start the first one
for(var i = 1; i < tasks.length; i++) p = p.then(tasks[i]);
p.then(function(result){
// all available here
});
或者更好,連續:
$.when.apply(tasks.forEach(function(t){ return t(); })).then(function(results){
// all done
})
我知道這是一個老問題,但最近情況發生了一些變化。
如果你使用外部庫很好,那么Bluebird promise庫有一個非常好的實現: Promise.each 。
例如
function helperFunc(zippyarray) {
return Promise.each(zippyarray, zippy => {
return someOperationThatReturnAPromise(zippy)
.then((singleResult) => {
// do something with the operation result if needed
})
}).then((originalArray) => {
// this happens only after the whole array is processed
// (result is the original array here)
return Promise.resolve(originalArray)
})
}
要跟蹤您使用這種方式的多個get-Requests:
var cnt = requestCnt;
function finished(){
if(--cnt)return;
// Your code here
}
for(var i = 0; i < requestCnt; ++i){
$.get('something.htm', {data:data}, function(data){
finished();
});
}
當請求得到答案時,您總是調用finished-function。 完成功能完成所有功能后完成工作。
今天如果我需要按順序執行 - 我會用async/await
來做:
//I'm assuming I'm inside an `async` function
zippyarray; // array of Zippy objects
for(const task of zippyArray) {
const result = await $.get({ ... });
// do stuff with result
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.