{"id":4176,"date":"2022-07-20T00:57:24","date_gmt":"2022-07-20T00:57:24","guid":{"rendered":"https:\/\/www.pythontutorial.net\/?page_id=4176"},"modified":"2025-04-02T06:48:38","modified_gmt":"2025-04-02T06:48:38","slug":"python-asyncio-wait","status":"publish","type":"page","link":"https:\/\/www.pythontutorial.net\/python-concurrency\/python-asyncio-wait\/","title":{"rendered":"Python asyncio.wait()"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you&#8217;ll learn about the <code>asyncio.wait()<\/code> function to run an iterable of awaitable objects concurrently.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id='introduction-to-the-python-asyncio-wait-function'>Introduction to the Python asyncio wait() function <a href=\"#introduction-to-the-python-asyncio-wait-function\" class=\"anchor\" id=\"introduction-to-the-python-asyncio-wait-function\" title=\"Anchor for Introduction to the Python asyncio wait() function\">#<\/a><\/h2>\n\n\n\n<p>The <code>asyncio.wait()<\/code> function runs an iterable of awaitables objects and blocks until a specified condition. <\/p>\n\n\n\n<p>Here&#8217;s the syntax of the <code>asyncio.wait()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-1\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">asyncio.wait(aws, *, timeout=<span class=\"hljs-literal\">None<\/span>, return_when=ALL_COMPLETED)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-1\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>The <code>asyncio.wait()<\/code> function has the following parameters:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>aws<\/code> is iterable of awaitable objects that you want to run concurrently.<\/li>\n\n\n\n<li><code>timeout<\/code> (either <code>int<\/code> or <code>float<\/code>) specifies a maximum number of seconds to wait before returning the result.<\/li>\n\n\n\n<li><code>return_when<\/code> indicates when the function should return. The <code>return_when<\/code> accepts one of the constants in the table below.<\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Constant<\/th><th>Description<\/th><\/tr><\/thead><tbody><tr><td><code>FIRST_COMPLETED<\/code><\/td><td>Return if at least one task (awaitable) is completed.<\/td><\/tr><tr><td><code>FIRST_EXCEPTION<\/code><\/td><td>Return when any awaitable is complete by raising an exception. If no task (awaitable) raises an exception, the <code>FIRST_EXCEPTION<\/code> is equivalent to <code>ALL_COMPLETED<\/code>.<\/td><\/tr><tr><td><code>ALL_COMPLETED<\/code><\/td><td>Return when all tasks (awaitables) are complete or cancelled.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Note that these constants are in the <code>asyncio<\/code> library so you can reference them like <code>asyncio.FIRST_COMPLETED<\/code><\/p>\n\n\n\n<p>The <code>asyncio.wait()<\/code> returns two sets:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-2\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">done, pending = <span class=\"hljs-keyword\">await<\/span> asyncio.wait(aws)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-2\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<ul id=\"block-95391e0d-c825-4754-b829-392a1cfd4309\" class=\"wp-block-list\">\n<li><code>done<\/code> is a set of awaitables that are done.<\/li>\n\n\n\n<li><code>pending<\/code> is a set of awaitables that are pending.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id='python-asyncio-wait-function-examples'>Python asyncio wait() function examples <a href=\"#python-asyncio-wait-function-examples\" class=\"anchor\" id=\"python-asyncio-wait-function-examples\" title=\"Anchor for Python asyncio wait() function examples\">#<\/a><\/h2>\n\n\n\n<p>The following example illustrates how to use the <code>asyncio.wait()<\/code> function:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-3\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">import<\/span> asyncio\n<span class=\"hljs-keyword\">from<\/span> asyncio <span class=\"hljs-keyword\">import<\/span> create_task\n\n\n<span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">APIError<\/span><span class=\"hljs-params\">(Exception)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">pass<\/span>\n\n\n<span class=\"hljs-keyword\">async<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">call_api<\/span><span class=\"hljs-params\">(message, result=<span class=\"hljs-number\">100<\/span>, delay=<span class=\"hljs-number\">3<\/span>, raise_exception=False)<\/span>:<\/span>\n    print(message)\n    <span class=\"hljs-keyword\">await<\/span> asyncio.sleep(delay)\n    <span class=\"hljs-keyword\">if<\/span> raise_exception:\n        <span class=\"hljs-keyword\">raise<\/span> APIError\n    <span class=\"hljs-keyword\">else<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> result\n\n\n<span class=\"hljs-keyword\">async<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">main<\/span><span class=\"hljs-params\">()<\/span>:<\/span>\n    task_1 = create_task(call_api(<span class=\"hljs-string\">'calling API 1...'<\/span>, result=<span class=\"hljs-number\">1<\/span>, delay=<span class=\"hljs-number\">1<\/span>))\n    task_2 = create_task(call_api(<span class=\"hljs-string\">'calling API 2...'<\/span>, result=<span class=\"hljs-number\">2<\/span>, delay=<span class=\"hljs-number\">2<\/span>))\n    task_3 = create_task(call_api(<span class=\"hljs-string\">'calling API 3...'<\/span>, result=<span class=\"hljs-number\">3<\/span>, delay=<span class=\"hljs-number\">3<\/span>))\n\n    pending = (task_1, task_2, task_3)\n\n    <span class=\"hljs-keyword\">while<\/span> pending:\n        done, pending = <span class=\"hljs-keyword\">await<\/span> asyncio.wait(\n            pending,\n            return_when=asyncio.FIRST_COMPLETED\n        )\n        result = done.pop().result()\n        print(result)\n\n\nasyncio.run(main())<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-3\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define the <code>APIError<\/code> class that extends the <code>Exception<\/code> class:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-4\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-class\"><span class=\"hljs-keyword\">class<\/span> <span class=\"hljs-title\">APIError<\/span><span class=\"hljs-params\">(Exception)<\/span>:<\/span>\n    <span class=\"hljs-keyword\">pass<\/span><\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-4\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Second, define the <code>call_api()<\/code> function that simulates an asynchronous operation:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-5\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">async<\/span> <span class=\"hljs-function\"><span class=\"hljs-keyword\">def<\/span> <span class=\"hljs-title\">call_api<\/span><span class=\"hljs-params\">(message, result=<span class=\"hljs-number\">100<\/span>, delay=<span class=\"hljs-number\">3<\/span>, raise_exception=False)<\/span>:<\/span>\n    print(message)\n    <span class=\"hljs-keyword\">await<\/span> asyncio.sleep(delay)\n    <span class=\"hljs-keyword\">if<\/span> raise_exception:\n        <span class=\"hljs-keyword\">raise<\/span> APIError\n    <span class=\"hljs-keyword\">else<\/span>:\n        <span class=\"hljs-keyword\">return<\/span> result<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-5\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Third, create three tasks that wrap the <code>call_api()<\/code> coroutines. Each coroutine returns a different number:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-6\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\">task_1 = create_task(call_api(<span class=\"hljs-string\">'calling API 1...'<\/span>, result=<span class=\"hljs-number\">1<\/span>, delay=<span class=\"hljs-number\">1<\/span>))\ntask_2 = create_task(call_api(<span class=\"hljs-string\">'calling API 2...'<\/span>, result=<span class=\"hljs-number\">2<\/span>, delay=<span class=\"hljs-number\">2<\/span>))\ntask_3 = create_task(call_api(<span class=\"hljs-string\">'calling API 3...'<\/span>, result=<span class=\"hljs-number\">3<\/span>, delay=<span class=\"hljs-number\">3<\/span>))\n\npending = (task_1, task_2, task_3)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-6\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<p>Finally, call the <code>asyncio.wait()<\/code> function to run the tasks inside a <code><a href=\"https:\/\/www.pythontutorial.net\/python-basics\/python-while\/\">while<\/a><\/code> loop. If all the tasks are complete, the pending will be empty, and the <code>while<\/code> loop will exit. In each iteration, we get the completed task from the <code>done<\/code> set and display the result:<\/p>\n\n\n<pre class=\"wp-block-code\" aria-describedby=\"shcb-language-7\" data-shcb-language-name=\"Python\" data-shcb-language-slug=\"python\"><span><code class=\"hljs language-python\"><span class=\"hljs-keyword\">while<\/span> pending:\n    done, pending = <span class=\"hljs-keyword\">await<\/span> asyncio.wait(\n        pending,\n        return_when=asyncio.FIRST_COMPLETED\n    )\n    result = done.pop().result()\n    print(result)<\/code><\/span><small class=\"shcb-language\" id=\"shcb-language-7\"><span class=\"shcb-language__label\">Code language:<\/span> <span class=\"shcb-language__name\">Python<\/span> <span class=\"shcb-language__paren\">(<\/span><span class=\"shcb-language__slug\">python<\/span><span class=\"shcb-language__paren\">)<\/span><\/small><\/pre>\n\n\n<h2 class=\"wp-block-heading\" id='summary'>Summary <a href=\"#summary\" class=\"anchor\" id=\"summary\" title=\"Anchor for Summary\">#<\/a><\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Use the <code>asyncio.wait()<\/code> to run tasks in an iterable concurrently.<\/li>\n<\/ul>\n<div class=\"helpful-block-content\" data-title=\"\">\n\t<header>\n\t\t<div class=\"wth-question\">Was this tutorial helpful ?<\/div>\n\t\t<div class=\"wth-thumbs\">\n\t\t\t<button\n\t\t\t\tdata-post=\"4176\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-asyncio-wait\/\"\n\t\t\t\tdata-post-title=\"Python asyncio.wait()\"\n\t\t\t\tdata-response=\"1\"\n\t\t\t\tclass=\"wth-btn-rounded wth-yes-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t\tclass=\"feather feather-thumbs-up block w-full h-full\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> Yes <\/span>\n\t\t\t<\/button>\n\n\t\t\t<button\n\t\t\t\tdata-response=\"0\"\n\t\t\t\tdata-post=\"4176\"\n\t\t\t\tdata-post-url=\"https:\/\/www.pythontutorial.net\/python-concurrency\/python-asyncio-wait\/\"\n\t\t\t\tdata-post-title=\"Python asyncio.wait()\"\n\t\t\t\tclass=\"wth-btn-rounded wth-no-btn\"\n\t\t\t>\n\t\t\t\t<svg\n\t\t\t\t\txmlns=\"http:\/\/www.w3.org\/2000\/svg\"\n\t\t\t\t\tviewBox=\"0 0 24 24\"\n\t\t\t\t\tfill=\"none\"\n\t\t\t\t\tstroke=\"currentColor\"\n\t\t\t\t\tstroke-width=\"2\"\n\t\t\t\t\tstroke-linecap=\"round\"\n\t\t\t\t\tstroke-linejoin=\"round\"\n\t\t\t\t>\n\t\t\t\t\t<path\n\t\t\t\t\t\td=\"M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17\"\n\t\t\t\t\t><\/path>\n\t\t\t\t<\/svg>\n\t\t\t\t<span class=\"sr-only\"> No <\/span>\n\t\t\t<\/button>\n\t\t<\/div>\n\t<\/header>\n\n\t<div class=\"wth-form hidden\">\n\t\t<div class=\"wth-form-wrapper\">\n\t\t\t<div class=\"wth-title\"><\/div>\n\t\t\t<textarea class=\"wth-message\"><\/textarea>\n\t\t\t<input type=\"button\" name=\"wth-submit\" class=\"wth-btn wth-btn-submit\" id=\"wth-submit\" \/>\n\t\t\t<input type=\"button\" class=\"wth-btn wth-btn-cancel\" value=\"Cancel\" \/>\n\t\t<\/div>\n\t<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn about the asyncio.wait() function to run an iterable of awaitable objects concurrently.<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":4104,"menu_order":19,"comment_status":"closed","ping_status":"closed","template":"","meta":{"footnotes":""},"class_list":["post-4176","page","type-page","status-publish","hentry"],"_links":{"self":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4176","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/comments?post=4176"}],"version-history":[{"count":1,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4176\/revisions"}],"predecessor-version":[{"id":7370,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4176\/revisions\/7370"}],"up":[{"embeddable":true,"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/pages\/4104"}],"wp:attachment":[{"href":"https:\/\/www.pythontutorial.net\/wp-json\/wp\/v2\/media?parent=4176"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}