Why push data to array on async/await? #44502
-
in func.js const p = (res) => {
return new Promise((resolve, reject) => {
res.push('2');
resolve(res);
});
}; in main.js const run = async () => {
const res = [];
res.push('1');
console.log('before...');
for (const item of res) console.log(item);
try {
await p(res); // call p func in func.js
console.log('after...');
for (const item of res) console.log(item); // ???
} catch (e) {
console.log('ERROR');
}
};
run();
/** result
* before...
* 1
* after...
* 1
* 2
*/
Why push 2 to res array if i don't assign returned new array? |
Beta Was this translation helpful? Give feedback.
Answered by
palamarchukser
Sep 3, 2022
Replies: 1 comment 3 replies
-
it happens because you are passing the link to an array. to avoid this behaviour
|
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
jiho5993
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it happens because you are passing the link to an array. to avoid this behaviour
await p([...res]); // call p func in func.js