[英]Q - Javascript promises wait for array to be filled
我是Q庫的新手,我了解Q對於數組方法的承諾存在的問題。 我有一個數組,其中包含各種鍵字符串,可以用延遲函數代替。 成功替換傳遞的數組后,我需要繼續執行現在完成的數組。 在這種情況下,我如何等待陣列被替換?
輸出看起來像
key: "p",
text: "Good morning %text%",
inside: key: "p"
text: "Good afternoon user"
inside: key: "p"
text: "This user has to be replaced."
如您所見,並非所有鍵都被替換了。
代碼樣例
var object = [];
object.key = "p";
object.text = "Good morning %text%";
object.inside = [];
object.inside.key = "p";
object.inside.text = "Good afternoon %text%";
object.inside.inside = [];
object.inside.inside.key = "p";
object.inside.inside.text = "This %text% has to be replaced.";
goDeep(object, 0);
console.log(object);
function goDeep(data) {
if (data instanceof Object) {
Object.keys(data).forEach(function(key) {
if (data[key] instanceof Object) {
goDeep(data[key]);
} else if (data[key].inside) {
goDeep(data[key].inside);
} else {
var match = scanText(data[key]);
if (match && !(match instanceof Boolean)) {
getServerData(match.input).then (function(response) {
var splitData = data[key].match(/%.*%/)[0].split(",");
for (ii = 0; ii < splitData.length; ++ii) {
splitData[ii] = splitData[ii].trim();
var replaceData = data[key].replace(splitData[ii], response);
// Data gets replaced here
data[key] = replaceData;
};
});
}
}
});
}
}
function scanText(data) {
var match = data.match("(%.*%)", "/g");
if (match) {
return match;
} else {
return false;
}
}
function getServerData(data) {
return Q.delay(1000).thenResolve("user");
}
首先讓我稍微糾正一下您真正想要的是什么,
使用JavaScript Prom遞歸調用異步函數
注意:我注意到Q庫,但是我敢肯定它將與其他承諾實現的庫相似
我會盡力簡化您的問題,所以我將逐步解釋
你需要all
方法
Q.all([
getWeather({name:'beirut'}),
getWeather({name:'paris'}),
getWeather({name:'madrid'})
]).then(function(beirut, paris, madrid){
// here I am sure that the 3 methods where completed
});
使用array.map
['beirut', 'paris', 'madrid'].map(function(city){ return getWeather(city) });
function getWeather(area) {
// this function should return a promise of the weather response
var deferred = Q.defer();
setTimeout(function () {
deferred.resolve({
name: 'beirut',
children: [{
name: 'sub area'
}, ...]
});
}, 300);
return deffered.promise;
}
function resolveChildren(parentArea, level) {
var deferred = Q.defer();
getWeather(parentArea).then(function (children) {
var promise = Q.all(children.map(function ( /* a sub area */ child) {
// if this a leaf then resolve the child, else go deeper and get the children of this child
// suppose child.isleaf return true if this is a leaf node
if (child.isleaf) {
return child;
}
return resolveChildren(child, level + 1);
}));
promise.then(function (children) {
parentArea.children = children;
deferred.resolve(parentArea);
});
}, function (err) {
// failed to get children for some reason
parentArea.children = null;
deferred.resolve(parentArea);
});
return deffered.promise;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.