Why did Myxios interceptor results keep gaining array layers? From concat() to spread syntax

April 25, 2025

The server returned 200. Why did adding an interceptor that changed nothing prevent the next layer from reading the response?

I hit a nested-array problem while using Myxios for login renewal in an asset-management system. Myxios is a fetch wrapper I wrote that lets you insert processing functions after a server responds. These are response interceptors. From the start, I wanted them to be composable functions. Checking login status and retrying a request each has inputs and outputs, and the same functions serve many concurrent requests. I wanted to judge a layer by what it receives and returns, with one less piece of state for interleaved requests to overwrite. This array bug shows why a shared contract for return values has to come first.1

Why could I read the first item but not the second?

Native fetch resolves to a Response. response.status gives its HTTP status code, while response.json() reads its body and parses it as a JavaScript value. Myxios wanted to keep the original response and each layer’s processing results, so it passed interceptors an array. The original response occupied index 0. If authentication retried a request, the new response could occupy index 1. The old README’s example takes item 1 and calls .json() on it.2

What if authentication found the login still valid? The application used return Promise.resolve(res). The easy mistake is misreading res. Substitute a locally created response for the server and combine the success branch with the old merge statement to reproduce the distinction. This adapted teaching example runs in a browser console.13

const response = new Response('{"assets":[]}');
const previous = [response];                 // 认证层收到的参数
const returned = await Promise.resolve(previous); // 成功分支原样交回
const results = [...previous, returned];     // 旧版 Myxios 合并结果

console.log(results[0].status);              // 200
console.log(results[1].status);              // undefined
console.log(Array.isArray(results[1]));      // true
console.log(results[1][0] === response);     // true

The last two lines explain the first two. Item 1 does contain the response, but behind one more array layer. An array has no .json() method, so results[1].json() from the README throws. Switching temporarily to results[1][0].json() works only for this branch. A successful retry returns the individual Response from fetch, so item 1 can already be read directly there. The type at the same index depends on which branch the request took. That’s the problem worth tracking back into the library.

Which line added the extra brackets?

Follow the calls to dispatchRequest and you’ll find array reduce. Functional programming calls this a fold: start with an initial value, take elements in order, and combine each with the preceding result to produce the next one. Here the collection being folded is the array of interceptor functions. The initial value is this fetch promise. Attaching one layer produces a new promise for the next layer. With just authentication and logging, it’s like fetchPromise.then(authenticationStep).then(loggingStep). Authentication waits for the initial request, and logging waits for authentication.3

Below is the old source’s reduce and merge function expanded, with variables renamed for readability. The first layer wraps the original response in [data]. From the second layer onward, data is the previous step’s accumulated result.3

function carry(previous, pendingResult) {
    return pendingResult.then(result => [...previous, result]);
}

function dispatch(fetchPromise, interceptors) {
    return interceptors.reduce((pending, intercept) => {
        return pending.then(data => {
            if (Array.isArray(data)) {
                return carry(data, intercept(data));
            }
            return carry([data], intercept([data]));
        });
    }, fetchPromise);
}

Focus on the array eventually produced by the promise carry returns. In an array literal, ...previous means “insert all items of previous in order.” The result after the comma occupies exactly one position, however large it is. Abbreviate a response as R and have two interceptors return their input unchanged:

LayerArray passed to interceptorValue returnedMerged value passed onward
First[R][R][R, [R]]
Second[R, [R]][R, [R]][R, [R], [R, [R]]]

Both layers returned the input unchanged, yet the last item of each round preserved the entire previous result. This also rules out asynchrony as the cause. await takes whatever value the promise resolves to. In the first example returned === previous is true. The extra brackets appear only when the two are placed in a new array.

How do I accept either one response or a batch of results?

I pasted [Response, [Response]] from the console into Cursor. It suggested changing [...param, res] to param.concat(res), which also appears in a local draft. How could one method accept both an individual retry response and a batch returned by an interceptor?4

MDN’s example letters.concat(1, [2, 3]) is a close match. The result ends in 1, 2, 3. One call illustrates both cases. The single 1 occupies one position. The two items in [2, 3] occupy one position each. The docs also specify the depth: “The concat method does not recurse into nested array arguments.” That may have been exactly what I wanted to confirm. At the interceptor boundary, appending only the items of the outer array prevents an extra wrapper while preserving the structure of each item.5

It’s clearer with the actual kinds of values:

const previous = ["原响应"];
console.log(previous.concat("重试响应"));       // ["原响应", "重试响应"]
console.log(previous.concat(["状态", "耗时"])); // ["原响应", "状态", "耗时"]
console.log(previous.concat([["资产 A"]]));     // ["原响应", ["资产 A"]]

Why not recursively flatten arrays to any depth? In functional programming you could use pattern matching and structural recursion: accept ordinary values one at a time, recursively apply the same rule to each array element, and let an empty array contribute zero items. If all you want are innermost values, there’s no need to know the depth in advance.

But in the third example, [["资产 A"]], the outer array says “this layer contributes one item”, and the inner ["资产 A"] is that item’s content. Recursive flattening would give the next layer the string "资产 A" (“asset A”). An empty asset-list result [[]] originally means “one result containing zero assets”. Fully flattening it to [] confuses it with “this layer contributed no result.” The dispatcher should unwrap only the outer handoff array and leave the inner data structure for application code to interpret.

If one concat() can handle both returns, why did I ultimately use spread syntax? Looking back, perhaps I found it easier to read. The old code already appended one value with [...previous, result]. I preserved that path and added a branch for “this layer returned an array”. Array.isArray(result) makes it explicit when elements should be appended individually. The following is adapted from the commit, omitting logs and an unnecessary Promise.resolve in the callback.6

function paramCarryPromise(previous, currentPromise) {
    return currentPromise.then(result => {
        if (Array.isArray(result)) {
            return [...previous, ...result];
        }
        return [...previous, result];
    });
}

The two branches differ by three dots. For a batch, ...result extracts its items. For a single Response, preserve the object itself. Writing ...result unconditionally would make JavaScript try to iterate a Response, which an ordinary Response doesn’t support. A string wouldn’t even throw: "OK" would quietly become two items, "O" and "K".

Separate “wait for the current interceptor” from “merge two values already available”, and the latter can be a pure function. For these ordinary arrays and response objects, that means computing a result solely from arguments without sending requests, reading tokens, or mutating inputs. This is an equivalent extraction of the two branches in the commit.6

function appendResult(previous, result) {
    const added = Array.isArray(result) ? result : [result];
    return [...previous, ...added];
}

The repair now has independently testable rules. Pass [] and the existing element count and order stay the same. Pass a Response and the new array gains one final item. Pass an array of two values and it gains two. Ordinary values suffice to run these checks. The new array reuses references to old elements, so you can verify nextResults[0] === previous[0] and confirm that previous.length is unchanged.

The operation concat performs is concatenation. Given existing results [[1]] and a new batch [2, 3], [[1]].concat([2, 3]) produces [[1], 2, 3]. The old first item [1] remains intact. If you append the batch as one item and call flat() on the whole result, [[1], [2, 3]].flat() gives [1, 2, 3], flattening old data too.5

In Myxios, reduce (fold) chains successive interceptors. Each round waits for the current result and only then performs this concatenation. Another familiar term, flatMap, means applying a function to every input and flattening the outputs one level. A standalone previous.concat(result) receives values that are already computed.37

Can two requests passing through authentication mix their results?

Suppose asset request A gets a 401 and the authentication function waits for a token refresh. Meanwhile, log request B gets a 200, and the same authentication function can finish B first. How can A resume with its own response?

One line in request() answers that. Every invocation calls dispatchRequest afresh, starting from that invocation’s fetch(url, options). A and B reuse the same interceptor functions but have separate initial promises. previous is local to each callback. While A waits, its callback retains A’s previous. When B appends a result, it creates B’s new array. B finishing first does not add its response to A’s results. Each chain proceeds in order, while different requests can interleave. That’s why I value this arrangement.86

The benefit has a boundary. If A and B both get 401 and both try to refresh the same login token, shallow-copying arrays doesn’t coordinate account state. To issue only one refresh, the application must explicitly share the in-flight refresh operation. Likewise, the new array still holds the original Response. If one layer consumes its body, later functions have to respect the one-use body contract. A functional approach helps me see which results belong to this invocation and which operations truly require coordination.

Back to the 200: what should I see after the fix?

Take the same Response through the success branch again. History is [R], authentication returns [R], and the fixed merge produces [R, R]. Now results[1] === results[0] is true. The caller really gets a Response at index 1. If a retry occurs, authentication returns a single new Response and the result is [original response, retry response]. The same access pattern reads item 1 on both paths.36

Add another pass-through interceptor and the array grows from two items to four. The dispatcher accumulates, but the interceptor has returned the entire already accumulated history. I’d document the contract as “the input is everything collected so far, and the output contains the items this layer wants to append.” A retry can return a new response. A logging layer that just observes can return Promise.resolve([]). If the caller expects to read index 1, at least one layer must actually supply it. The code can settle how arrays merge. The interface still has to say what each position means.

References

Footnotes

  1. CaiBorui. (2025, April 25). HttpHandler.js [AssetMan 本地提交 0dde73f,notAuthorizedInterceptor 读取 res[0] 及末行返回 Promise.resolve(res)]. 作者留存的 Git 仓库。 ↩ ↩2

  2. Cai, B. [S2thend]. (2024, April 2). Myxios [修复前版本,README 的一次性拦截器示例,说明如何读取原响应和后续结果]. GitHub. Use a one time interceptor。 ↩

  3. Cai, B. [S2thend]. (2024, April 2). Myxios [提交 15255a8,修复的直接父版本]. GitHub. dispatchRequest 如何把累计结果传给各层、paramCarryPromise 如何追加结果。 ↩ ↩2 ↩3 ↩4 ↩5

  4. CaiBorui. (2025, April 24–25). Fixing Nested Array Issues in Responses [Cursor 开发对话、编辑历史与 Firefox 访问记录,作者留存]. 消息 1 贴出了嵌套结果,约 15:14 的助手回复建议 param.concat(res);15:15:26 的本地草稿已有此写法。约 16:11 的消息 9 描述了想得到的扁平结果序列。首次留存的 MDN 访问在 16:28:10,次晨 08:43:11 重访;两次 URL 均无小节锚点。提问按相邻助手回复定位,均为北京时间。文章按修复提交日期归档。 ↩

  5. MDN contributors. (2025, April 3). Array.prototype.concat() [英文文档源码,提交 702cd9e]. MDN Web Docs. Description 第 1 段,引文末句、Concatenating values to an array 示例。日期为访问前该文档最近一次源码修订。 ↩ ↩2

  6. Cai, B. [S2thend]. (2025, April 25). Fix bug (causing deeper nested array each step on interceptor chain) on chaining responses from intercepter chain [提交 d8baecc]. GitHub. 修复前后差异、合并结果的两个分支。 ↩ ↩2 ↩3 ↩4

  7. MDN contributors. (n.d.). Array.prototype.flatMap() [Description]. MDN Web Docs. 逐项映射并展开一层。另见 GHC Team. (n.d.). Data.List [base 4.17.0.0,concatMap]. GHC. concatMap 的类型与示例。 ↩

  8. Cai, B. [S2thend]. (2025, April 25). Myxios [提交 d8baecc,每次请求创建处理链的入口]. GitHub. Myxios.request、dispatchRequest。 ↩

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-04-25). Why did Myxios interceptor results keep gaining array layers? From concat() to spread syntax. https://caiborui.com/blog/2025-04-25-zh-myxios-concat-nested-interceptor-results-entrans

@misc{borui2025-d4daf78c,
  author = {borui},
  title = {{Why did Myxios interceptor results keep gaining array layers? From concat() to spread syntax}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-04-25-zh-myxios-concat-nested-interceptor-results-entrans}
}