javascriptpromisees6-promisefetch-apiisomorphic-fetch-api

How to make fetch promise resolve without using .then syntax?


First things first, I made sure to write a quick demo of the issue I'm talking about here https://codesandbox.io/s/exciting-swirles-7cs3s

But essentially, using the isomorphic-fetch library, I'm running into an issue where I can't really get the value, or you might say, resolution, of the fetch() function.

import fetch from "isomorphic-fetch";

async function test() {
  return await fetch("https://google.com", { mode: "no-cors" });
}

let t = test();
console.log(t);

The outcome of which is

enter image description here

Now I've also considered the other way of using fetch() like this

fetch("https://google.com", { mode: "no-cors" })
  .then(response => response.text())
  .then(data => console.log(data));

which actually delivers a string, but I prefer doing it the first way, if possible? It's also very possible I'm not using fetch correctly.


Solution

  • Try it like this:

    import fetch from "isomorphic-fetch";
    
    async function test() {
      const response = await fetch("https://google.com", { mode: "no-cors" });
      return response.text();
    }
    async function main() {
      let t = await test();
      console.log(t);
    }
    main();
    

    You need to await the promise, and that means you need an async function.