Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 530
notacorn Avatar asked Oct 27 '25 02:10

notacorn


1 Answers

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.

like image 178
see sharper Avatar answered Oct 29 '25 17:10

see sharper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!