JSFiddle - React, Tailwind, and code Playground
by karthick6891
JavaScript
'use strict';
var arr1 = [2, 4, 6, 8, 10];
var arr = [];
// Put item i to output array
function putItem(i) {
var temp_arr = arr;
// Clousre to keep the original value of arr at this point
function returnResult() {
return new Promise(
(resolve, reject) => {
let thisObject = {
array: arr1,
index: i
}
console.log("Async code started: putting item arr1[" + thisObject.index + "] = " + thisObject.array[thisObject.index]);
setTimeout(function () {
arr.push(thisObject.array[thisObject.index]);
resolve(thisObject); // "Release" the protected resource (arr1[i])
}, Math.random() * 2000 + 1000);
}
);
}
return returnResult();
}
var op1 = putItem(2);
var op2 = putItem(3, arr);
op1.then(function (result) {
console.log(result.array[result.index] + " was inserted")
});
op2.then(function (result) {
console.log(result.array[result.index] + " was inserted")
});
Promise.all([op1, op2]).then(function(){
arr1[3] = 7;
});
setTimeout(() => {
console.log(arr,arr1);
}, 3000);