Yokida Yokida - 14 days ago 5
Javascript Question

Array.forEach Callback at the end

I'm using

Array.forEach
function of javascript to get a different message for each element of a list. So I'm using
forEach
function and I'm looking for a
way
to execute my
callback
function
cb(result)
when the foreach as finished to both execute
.forEach
and
msgAfterTimeout
. I read that there was something called
promises
but I don't really get how I can use them here.

function msgAfterTimeout (who, timeout, onDone) {
setTimeout(function () {
onDone(" Hello " + who + "!");
}, timeout);
}
var test="";
var list = [{name:"foo",surname:"bar"},{name:"Jean",surname:"dupond"}];

function dispName(cb)
{
list.forEach(function(item, index)
{
msgAfterTimeout(item.name, 200, function (msg)
{
test=msg+"\n";

});
cb(result);

});

}

dispName(function(data){
console.log(data);
});

Answer

Here's your example with Promises:

var list = [{name: "foo", surname: "bar"}, {name: "Jean", surname: "dupond"}];


function msgAfterTimeout(who, timeout) {
    return new Promise(resolve =>
        setTimeout(
            () => resolve(" Hello " + who + "!"),
            timeout)
    );
}


Promise.all(
    list.map(item => msgAfterTimeout(item.name, 200))
).then(
    result => console.log(result.join('\n'))
);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise