I would like my function to return array of promises. The code inside the function is asynchronous. I need to check each element for its type and do some processing. I do not know how the function can return all promises - once it has done the asynchronous processing. 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)
The important thing is to create the promise immediately and do the asynchronous stuff inside of it:
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;
}
I would also recommend to use map
instead of forEach
+ push
.
Based on the excellent answer from Bergi, this is my contribution:
1- Function addFeatures
with 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- A function to test the result from addFeatures
.
If you don't manage correctly the answer from code above, sometimes the resolve
from the asynchronous placeholder promise
becomes pending
and returns undefined
. That's why you need Promise.all
:
function foo(){
return Promise.all(addFeatures([1, 'text'])).then(values => {
return values;
}, function() {
throw 'Promise Rejected';
});
}
3- Calling your function above
foo().then(function(result) {
console.log("result => " + result);
}).catch(function(error) {
console.log("error => " + error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.