E
E
Evgeny Kucherenko2017-06-08 18:02:39
Yii
Evgeny Kucherenko, 2017-06-08 18:02:39

How to perform synchronous iteration of an array?

Can you tell me how to do synchronous iteration? The console should output sequentially 1, 2, ... with different delays and return an array of values ​​* 2

let array = Array.from({ length: 10 }, (v, k) => k)

const fn = (el) =>
  setTimeout(() => {
  	console.log(el)
        return el * 2;
  },
  1000 * Math.random()
)

console.log(array.map(fn))

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Dmitry, 2018-10-11
@slo_nik

Try changing dataType in ajax request to "jsonp"

$.ajax({
             url: '//domain2.com/get-widget',
             data: {project: 1},
             type: 'post',
             crossDomain:true,
             async:true,
             dataType: 'jsonp',
             success: function (data, status) {
                     if (data.status == 'ok') {
                         $('body').append(data.html)
                     }
             }
         })

JSONP
Although I think this is not the best solution.
Yii2 has a Cors filter . Perhaps it will help you.
https://ru.wikipedia.org/wiki/Cross-origin_resource...

V
Victor L, 2017-06-09
@evgenyspace

arr = Array.from({ length: 10 }, (v, k) => k);

function timeout(val){
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            console.log(val);
            resolve();
        }, 1000 * Math.random());
    });
}
(async () => {
  for (const val of arr) {
    await timeout(val);
  }
  console.log('Расчет окончен');
})();

N
Negwereth, 2017-06-08
@Negwereth

Map first, then withdraw?

I
Islam Ibakaev, 2017-06-09
@devellopah

try like this

let array = Array.from({ length: 10 }, (v, k) => k);

const fn = (el) => {
  setTimeout(() => { console.log(el) }, 100 * el);
  return el * 2;
};

console.log(array.map(fn));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question