Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Verarbeiten von Promises - mit Fetch und API Adapter

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Verarbeiten von Promises - mit Fetch und API Adapter

    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      SMARTY.ML @Asgothian last edited by SMARTY.ML

      Nächste Versuch

      1.PNG

      10:23:19.227 var out = await fetch('http://192.168.31.3:8087/get/alias.0.Klimaanlage.Power_aktuell.ACTUAL?prettyPrint');
      console.log(out);
      10:23:19.256
      Response { type: "cors", url: "http://192.168.31.3:8087/get/alias.0.Klimaanlage.Power_aktuell.ACTUAL?prettyPrint", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }
      ​
      body: ReadableStream { locked: false }
      ​​
      locked: false
      ​​
      <prototype>: ReadableStream.prototype { cancel: cancel(), getReader: getReader(), tee: tee(), … }
      ​
      bodyUsed: false
      ​
      headers: Headers {  }
      ​​
      <prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … }
      ​
      ok: true
      ​
      redirected: false
      ​
      status: 200
      ​
      statusText: "OK"
      ​
      type: "cors"
      ​
      url: "http://192.168.31.3:8087/get/alias.0.Klimaanlage.Power_aktuell.ACTUAL?prettyPrint"
      ​
      <prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
      ​​
      arrayBuffer: function arrayBuffer()
      ​​
      blob: function blob()
      ​​
      body: 
      ​​
      bodyUsed: 
      ​​
      clone: function clone()
      ​​
      constructor: function ()
      ​​
      formData: function formData()
      ​​
      headers: 
      ​​
      json: function json()
      ​​
      ok: 
      ​​
      redirected: 
      ​​
      status: 
      ​​
      statusText: 
      ​​
      text: function text()
      ​​
      type: 
      ​​
      url: 
      ​​
      Symbol(Symbol.toStringTag): "Response"
      ​​
      <get body()>: function body()
      ​​
      <get bodyUsed()>: function bodyUsed()
      ​​
      <get headers()>: function headers()
      ​​
      <get ok()>: function ok()
      ​​
      <get redirected()>: function redirected()
      ​​
      <get status()>: function status()
      ​​
      <get statusText()>: function statusText()
      ​​
      <get type()>: function type()
      ​​
      <get url()>: function url()
      ​​
      <prototype>: Object { … }
      
      S 1 Reply Last reply Reply Quote 0
      • S
        SMARTY.ML @SMARTY.ML last edited by SMARTY.ML

        async function getjson(url = '', data = {}) {
                const response = await fetch(url, {
                });
                return response.json();
            }
            
        
        async function get_api_value(ip,id)
        {
          let o;
          await getjson('http://' + ip + '/get/' + id + '?prettyPrint')
            .then(data => 
                  {
                  o = data;
                  });
          return o.val;
        }
        

        Meine Lösung: Ich deklariere eine weitere Variable, welche ich im .then(...) mit den Daten Fülle und gebe diese im return aus. Im Unterschied zu vorher muss ich nicht mit dem Promise weiter arbeiten. Innerhalb von .then(...) kann ich nämlich auf das Response als Object/JSON zugreifen, so wie oben beschrieben.

        Ich glaube ich habe damit eine Lösung, aber schlaut mich bitte mal auf.

        AlCalzone 1 Reply Last reply Reply Quote 0
        • AlCalzone
          AlCalzone Developer @SMARTY.ML last edited by AlCalzone

          @smarty-ml sagte in Verarbeiten von Promises - mit Fetch und API Adapter:

          Ich glaube ich habe damit eine Lösung, aber schlaut mich bitte mal auf.

          await und .then zusammen macht in 99,99% der Fälle keinen Sinn.

          let o;
          await getjson(...).then(data => {
            o = data;
          });
          

          ist äquivalent zu

          let o = await getjson(...);
          

          Und um deine beiden Funktionen in eins zu packen, reicht das:

          async function get_api_value(ip,id) {
            // 1. HTTP request machen
            const response = await fetch('http://' + ip + '/get/' + id + '?prettyPrint');
            // 2. Antwort umwandeln
            return response.json().val;
          }
          
          1 Reply Last reply Reply Quote 0
          • S
            SMARTY.ML last edited by SMARTY.ML

            OKAY, danke ich habe es!
            Der Fehler lag also in meinen Gedankengängen beim .then und await.
            Ich schlaue mich da mal auf ^^

            Zum Verständnis:

            Await und .then erzwingen eine Pause, bis die entsprechende Funktion beendet ist. Lasse ich in der finalen Funktion das await weg, so führt er beide Befehle zum gleichen Zeitpunkt durch und findet daher kein Objekt "response"?

            Richtig?

            AlCalzone 1 Reply Last reply Reply Quote 0
            • AlCalzone
              AlCalzone Developer @SMARTY.ML last edited by AlCalzone

              @smarty-ml Eine async-Funktion gibt implizit einen Promise (ein Wert, der erst später "fertig" ist) zurück. Wenn du diesen nicht mit await abwartest, geht's wie du schon erkannt hast sofort weiter, ohne dass das Ergebnis schon da ist.

              await nutzt übrigens unter der Haube auch .then, macht den Ablauf des Codes aber klarer.

              1 Reply Last reply Reply Quote 1
              • F
                fastfoot @SMARTY.ML last edited by

                @smarty-ml sagte in Verarbeiten von Promises - mit Fetch und API Adapter:

                var out = await fetch('http://192.168.31.3:8087/get/alias.0.Klimaanlage.Power_aktuell.ACTUAL?prettyPrint');
                let o=JSON.parse(out);
                let val =o.val;
                log(val);
                Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
                    <anonymous> debugger eval code:7
                    async* debugger eval code:10
                
                

                dein out ist bereits ein Objekt. Lasse Zeile 2 Weg und in Zeile 3 let val=out.val

                1 Reply Last reply Reply Quote 0
                • Karel Puhli
                  Karel Puhli last edited by

                  Nabend!
                  Das Thema ist etwas älter, aber vielleicht antwortet ja trotzdem jemand.... 🙂
                  Ich möchte eine einfache fetch api Anfrage durchführen. Leider bekomme ich eine Fehlermeldung.
                  Hat jemand ne Idee?

                  Hier mein Code:

                  import fetch from 'node-fetch'; 
                  
                  async function getWetter() {
                      const data = await fetch("https://api.weather.gov/gridpoints/OKX/35,35/forecast");
                      const ergebnis = data.json();
                      console.log(ergebnis);
                  }
                  
                  getWetter();
                  

                  Hier die Fehlermeldung:

                  18:57:36.521	info	javascript.0 (202) Start javascript script.js.Javascript.ioBroker.Test.fetch
                  18:57:36.541	error	javascript.0 (202) script.js.Javascript.ioBroker.Test.fetch compile failed: at script.js.Javascript.ioBroker.Test.fetch:1
                  18:57:45.066	info	javascript.0 (202) Stop script script.js.Javascript.ioBroker.Test.fetch
                  

                  Hier die Ausgabe von npm ls node-fetch:

                  root@iobroker:/opt/iobroker# npm ls node-fetch
                  iobroker.inst@3.0.0 /opt/iobroker
                  ├─┬ iobroker.backitup@2.6.16
                  │ └─┬ google-auth-library@8.7.0
                  │   └─┬ gaxios@5.0.2
                  │     └── node-fetch@2.6.9
                  ├─┬ iobroker.iot@1.14.2
                  │ └─┬ canvas@2.11.0
                  │   └─┬ @mapbox/node-pre-gyp@1.0.10
                  │     └── node-fetch@2.6.9 deduped
                  └─┬ iobroker.javascript@6.1.4
                    └── node-fetch@3.3.1
                  
                  root@iobroker:/opt/iobroker# 
                  

                  Schönen Abend und Grüße!!!

                  Karel

                  1 Reply Last reply Reply Quote 0
                  • Karel Puhli
                    Karel Puhli last edited by

                    Keiner ne Idee???

                    Wal 1 Reply Last reply Reply Quote 0
                    • Wal
                      Wal Developer @Karel Puhli last edited by

                      @karel-puhli ,
                      ich denke das du das Modul fetch hier hinzufügen musst, ist aber ohne Gewähr.
                      Screenshot 2023-04-25 192439.png

                      Karel Puhli 1 Reply Last reply Reply Quote 0
                      • Karel Puhli
                        Karel Puhli @Wal last edited by Karel Puhli

                        @wal

                        Hi Walter!
                        Danke für Deine Antwort!
                        Ist in beiden Zeilen drin!

                        1 Reply Last reply Reply Quote 0
                        • First post
                          Last post

                        Support us

                        ioBroker
                        Community Adapters
                        Donate

                        515
                        Online

                        31.8k
                        Users

                        80.0k
                        Topics

                        1.3m
                        Posts

                        6
                        19
                        1481
                        Loading More Posts
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes
                        Reply
                        • Reply as topic
                        Log in to reply
                        Community
                        Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
                        The ioBroker Community 2014-2023
                        logo