0
votes

as the title says, I am stuck with some interesting issue with promises. So i have a file that export object with a method, this function gets 2 values and return a setTimeout. the function gets a redux action (function dispatch) and a value for setTimeout. The problem is when I want to make a fetch call and then when the promise fulfilled dispatch the action. the most close I got it this code:

const products = async () => {
    const response = await fetch('http://localhost:3009/products');
    const data = await response.json();
    return data
}

const TIMEOUT = 100

export default {
    getProducts: (cb, timeout) => setTimeout(() => {
        new Promise(resolve => resolve(products)).then((data)=> cb(data))
    }, timeout || TIMEOUT),
}

Thanks to all who try to help

2

2 Answers

0
votes

Your default export is difficult to read and probably buggy. Try declaring a const and exporting that.

Also, your Promise logic makes no-or-little sense: once timeout millis have passed, create a Promise automatically resolved into a pointer to the function products, and then call cb with that function as an argument.

const products = async () => {
    const response = await fetch('http://localhost:3009/products');
    const data = await response.json();
    return data
}

// Helper function to promisify setTimeout
const delay = (millis) => new Promise( resolve => setTimeout(resolve, millis));

// Use default argument value
const TIMEOUT = 100;
const getProducts = async (cb, timeout=TIMEOUT) => {
  await delay(timeout);
  const data = await products();
  cb(data);
}

export default getProducts
0
votes

OK my code is actually works! I had a problem with the server.