# Promise.inSeries()

[JS](/web/js.md) ⟩ [async](/web/js/async.md) ⟩ [Promise](/web/js/async/promise.md) ⟩ [chaining](/web/js/async/promise/chaining.md) ⟩ Promise.inSeries()

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit：[Promise in series](https://replit.com/@pegasusroe/Promises-in-series#index.js)

```javascript
// 🔸 Promise.inSeries()
Promise.inSeries = function(promises) {

    // store results from promises 
    const results = [];
    
    // ⭐ start with a "trivial" Promise
    let p = Promise.resolve();

    // ⭐ Promise chain of arbitrary length
    for (const promise of promises) {
        p = p.then(value => {
            results.push(value);    // save resolved value
            return promise;         // return next promise
        });
    }

    // ⭐ return a Promise for `results`.
    return p.then(value => {
        results.push(value); // ⭐ save last resolved value
        results.shift();     // ⭐ remove value from first "trivial" promise
        return results;
    });
    
};
```

💈範例：

```javascript
// test 1
Promise.inSeries([
    Promise.resolve(1),
    Promise.reject('error in promise #2'),
    Promise.resolve(3),
]).then(results => 
    console.log(results)
).catch(error => {
    console.log(error)        // ⛔ rejected: "error in promise #2"
});

// test 2
Promise.inSeries([
    new Promise(resolve => setTimeout(resolve, 2000, 1)),
    new Promise(resolve => setTimeout(resolve, 1000, 2)),
    Promise.resolve(3),
]).then(results => 
    console.log(results)      // ✅ fulfilled: [ 1, 2, 3 ]
).catch(error => {
    console.log(error)
});
```

{% endtab %}

{% tab title="📗 參考" %}

* [ ] JavaScript: The Definitive Guide (13.2.7 Promises in Sequence)
  {% endtab %}
  {% endtabs %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://lochiwei.gitbook.io/web/js/async/promise/chaining/promise.inseries.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
