非同期イテレータオブジェクトを作成しましょう


ヘイ!👋
この動画はお気に入りから削除されています🤞
ハッピーサンクスギビング🎉🦃
昨日、短い記事を書いただけで、最後のsnipedコードをチェックしてください🙏
今日、私たちは、その簡単な対話型オブジェクトをより便利にするつもりです😊
私たちはRXJSからForkJoinのようないくつかの演算子を持っています.そして、それは観察可能なオブジェクトの配列を完了させるでしょう🤔)
複数のデータから複数のデータを取得しようとすると、それは本当に完全な機能です📌
更新は簡単です、最初にどのようにiterableオブジェクトの外観のように見てみましょう
const ourOwnIterable = {
    value: [1, 2, 3, 4, 5],
    index: 0,
    [Symbol.iterator]() {
        return {
            next: () => {
                if(this.value.length === this.index) {
                    return {
                        value: null,
                        done: true
                    }
                }
                this.index++;
                return {
                    value: this.value[this.index - 1],
                    done: false
                }
            }
        }
    }
}
そして、我々はループのためにそうように使用して値を投げることができた
for (const el of ourOwnIterable) {
 console.log(el)
}
私たちのシナリオをクリアしましょう、我々はいくつかのデータを取得するためにいくつかのURLを持っているし、それらを1つずつスローし、その結果を参照してくださいに行く能力を持っている😏
最初に値の代わりにURLを使うつもりです
const ourOwnIterable = {
    urls: [],
    ...
それから、我々は使用するつもりですasyncIterator メソッドSymbol の代わりにiterator
....
 [Symbol.asyncIterator]() {
        return {
        ....
我々が使用するようにfetch URLを呼び出すためにawait 演算子、我々は更新する必要がありますnext() 関数で、async 接頭辞
...
return {
 next: async () => {
...
今、我々はURLからデータを取り出して、抽出して、返すために我々の論理を実装する準備ができています
next: async () => {
    if (this.urls.length === this.index) {
        return {
            value: null,
            done: true
        }
    }
    this.index++;
    const fetchedResult = await fetch(this.urls[this.index - 1]);
    const extractedData = await fetchedResult.json();
    return {
        value: extractedData,
        done: false
    }
}
私たちのフェッチソリューションを内側に置くのは良い習慣ですtry-catch 誤り処理をする
try {
    const fetchedResult = await fetch(this.urls[this.index - 1]);
    const extractedData = await fetchedResult.json();

    return {
        value: extractedData,
        done: false
    }
} catch (e) {
    return {
        value: {
            url: this.urls[this.index - 1],
            error_message: `Got error ${e.message}`
        },
        done: false
    }
}
今、私たちのiterableオブジェクトはループのために使用する準備ができています😄
for await (const res of ourOwnIterable) {
        console.log(res);
    }
では、いくつかのURLを渡して何が起こるか見てください.🤪
async function fetchAllUrls(urls) {
    ourOwnIterable.urls = urls;
    for await (const res of ourOwnIterable) {
        console.log(res);
    }
}

fetchAllUrls([
    'https://jsonplaceholder.typicode.com/todos/1',
    'https://jsonplaceholder.typicode.com/todos/2',
    'https://jsonplaceholder.typicode.com/todos/3'
]);
その結果を見るには、HTMLドキュメントを使用する必要がありますfetch() メソッド🤔)
プットは、このようなものに置く
Object { userId: 1, id: 1, title: "delectus aut autem", completed: false }
Object { userId: 1, id: 2, title: "quis ut nam facilis et officia qui", completed: false }
Object { userId: 1, id: 3, title: "fugiat veniam minus", completed: false }
それで🤸‍♂️
今、私たちは、美しいエラーハンドラで1つずつURLの配列を取得できる独自のiterableオブジェクトを持っています
最後のフルスクリプトは次のようになります
const ourOwnIterable = {
    urls: [],
    index: 0,
    /**
     * 
     * @returns {{
     * next: (function(): Promise<{value: null, done: boolean}
     * |{value: any, done: boolean}
     * |{value: {error_message: string, url: *}, done: boolean}
     * |undefined>)}}
     */
    [Symbol.asyncIterator]() {
        return {
            next: async () => {
                if (this.urls.length === this.index) {
                    return {
                        value: null,
                        done: true
                    }
                }
                this.index++;
                try {
                    const fetchRes = await fetch(this.urls[this.index - 1]);
                    const extractedData = await fetchRes.json();

                    return {
                        value: extractedData,
                        done: false
                    }
                } catch (e) {
                    return {
                        value: {
                            url: this.urls[this.index - 1],
                            error_message: `Got error ${e.message}`
                        },
                        done: false
                    }
                }
            }
        }
    }
}

/**
 * 
 * @param urls
 * @returns {Promise<void>}
 */
async function fetchAllUrls(urls) {
    ourOwnIterable.urls = urls;
    for await (const res of ourOwnIterable) {
        console.log(res);
    }
}

fetchAllUrls([
    'https://jsonplaceholder.typicode.com/todos/1',
    'https://jsonplaceholder.typicode.com/todos/2',
    'https://jsonplaceholder.typicode.com/todos/3'
]);

ありがとうございました🤝
あなたが楽しむ望み❤