![](/img/trans.png)
[英]How to wait promises ad push data to array in forEach loop [react]
[英]How to wait for all promises being added to array in forEach loop?
我希望我的函數返回諾言數組。 函數內部的代碼是異步的。 我需要檢查每個元素的類型並進行一些處理。 我不知道該函數如何返回所有的諾言-一旦完成異步處理。 的jsfiddle
function addFeatures (input) {
var result = [];
input.forEach(function (el) {
if (Number.isInteger(el)) {
// placeholder asynchronous
setTimeout(function () {
result.push(
new Promise(function (resolve, reject) {
resolve(el.toString() + 'string')
})
)
}, 2000);
}
else {
// placeholder synchronous
result.push(
new Promise(function (resolve, reject) {
resolve(el + 'string')
}));
}
})
return result;
};
var arr = [1, 'text']
var final = addFeatures(arr)
// should log 2 promises but logs only 1 - the synchronous
console.log(final)
最重要的是要立即創建的承諾,做它里面的東西異步:
function addFeatures (input) {
var result = [];
input.forEach(function (el) {
result.push(new Promise(function (resolve, reject) {
if (Number.isInteger(el)) {
// placeholder asynchronous
setTimeout(function () {
resolve(el.toString() + 'string')
}, 2000);
} else {
// placeholder synchronous
resolve(el + 'string')
}
});
});
return result;
}
我還建議使用map
而不是forEach
+ push
。
基於貝爾吉的出色回答,這是我的貢獻:
1-函數addFeatures
與array.map
:
function addFeatures (input) {
return input.map(function(el) {
return new Promise(function (resolve, reject) {
if (Number.isInteger(el)) {
setTimeout(resolve, 2000, el.toString() + 'string');
/* setTimeout(reject, 2000, el.toString() + 'string'); //for reject */
}
else {
resolve(el + 'string');
/* reject(el + 'string'); //for reject */
}
})
});
};
2-測試addFeatures
結果的addFeatures
。
如果您不能正確地管理以上代碼的答案, 有時 asynchronous placeholder promise
的resolve
將變為pending
並返回undefined
。 這就是為什么您需要Promise.all
的原因:
function foo(){
return Promise.all(addFeatures([1, 'text'])).then(values => {
return values;
}, function() {
throw 'Promise Rejected';
});
}
3-在上面調用您的函數
foo().then(function(result) {
console.log("result => " + result);
}).catch(function(error) {
console.log("error => " + error);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.