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

4.9k views Asked by At

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.

3

There are 3 answers

5
see sharper On BEST ANSWER

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.

1
CygnusOlor On

fetch will return a promise, not a string. In your second example you call .text() on it. You will have to do something similar in asyc/await

1
Karan On

Use t.then(res => console.log(res)); it will return response object.

As you have async function test and you are not awaiting it like await test() so it will return promise.

As per your comment you should be using await test(). But you can only use await inside async so I suggest to use wrapper function like below.

import fetch from "isomorphic-fetch";

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

async function wrapper() {  
  let t = await test();
  console.log(t.text());
}

wrapper();