in file1.js

const p = (res) => {
    return new Promise((resolve, reject) => {
        res.push('2');
        resolve("hi");
    });
};

in file2.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
 */

따로 리턴값을 받지 않고(res배열을 할당하지 않고) 그냥 await로 실행해줬을 뿐인데, 2가 push되어 있는 현상을 발견하여 깃헙에 질문해봤었다.

이런 현상이 발생하는 이유는

JS의 배열은 객체에 대한 참조이기 때문이다. (C의 pointer같은 개념)

Call By Value VS Call By Reference

그래서 코드에서 reference로 전달하고 2를 push하여 전달되는 것이다.

resolve에 대한 이유가 아니기 때문에 resolve에 배열을 넣지 않아도 된다.

아래 링크는 깃허브 nodejs에 질문했었던 내용과 답변이다.

Why push data to array on async/await? · nodejs · Discussion #44502