1
  • app.js

    import test from "./asyncTest";
        test().then((result)=>{
        //handle my result
    });
    
  • asyncTest.js

    const test = async cb => {
        let data = await otherPromise();
        let debounce = _.debounce(() => {
    
       fetch("https://jsonplaceholder.typicode.com/posts/1")
            .then( => response.json())
            .then(json => json );
        }, 2000);
    };
    export default test;
    

The fetch result "json" I intend to return is unable to be the return value of "test" function since the value only available in an inner function scope such as debounce wrapper. Since above reason, I tried to pass a callback function and wrap the callback to be Promise function(pTest) as below.

const test = async cb => {
  let debounce = _.debounce(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
      .then(response => response.json())
      .then(json => cb(null, json))
      .catch(err => cb(err));
  }, 2000);
};
const pTest = cb => {
  return new Promise((resolve, reject) => {
    test((err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
};
export default pTest;

This way works for me, but I'm wondering if it's correct or are there any ways to solve this scenario?

JasonHsieh
  • 553
  • 1
  • 6
  • 20
  • 5
    Using `async` without `await` has no utility if you expect a return value. What is the purpose of debouncing the fetch request? – Randy Casburn Apr 17 '18 at 03:35
  • I have to use other await promises in the test function. Just edited, thanks. The purpose of using deounce doesn't matter, I try to express the value I need to return is inside another function. setTimeout maybe be a better example. – JasonHsieh Apr 17 '18 at 03:46
  • I've modified my answer to include your await. Please review – Randy Casburn Apr 17 '18 at 04:12
  • Can you please indent your code properly? It's really hard to read. Also, your `test` function does not return anything, and never calls the debounced function, is that intended? – Bergi Apr 17 '18 at 07:51
  • For starters, you should add return to your fetch function call, so that it returns the chained promise. Also the async cb doesn't make sense, you are not using it in callback "mode" but in promises mode, I see you are not using it anyway, but it is very confusing to readers. – Ralph Apr 24 '18 at 16:21
  • @Ralph Thanks for your reply. I think it's better to put callback function over here since _.debounce doesn't return value. refer to https://stackoverflow.com/a/37836720/6414615 – JasonHsieh Apr 25 '18 at 04:55

1 Answers1

1

The fetch API already returns a promise. Wrapping it in another Promise object is actually an anti-pattern. it is as simple as the code below:

/*export*/ async function test() {
  let data = await otherPromise();
  return fetch("https://jsonplaceholder.typicode.com/posts/1")
    .then(response => response.json())
    .then(json => {
      return {
        json: json,
        data: data
      }
    });
};

function otherPromise() {
  return new Promise((resolve, reject) => {
    resolve('test for data value');
  });
}

// In index.js call
test().then(res => {
  console.log(res)
});
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • Remove both the `async` and `await`. Neither is required or useful here. You're just returning a promise from a regular function. – jfriend00 Apr 17 '18 at 03:50
  • @jfriend00 - OP wants to operate on other async functions and the response inside the test function and outside test as a return value. Also wants to do so in synch way. – Randy Casburn Apr 17 '18 at 03:56
  • There's no point to `return await fetch()`. The `await` is pointless. The `async` function always returns a promise. So, just do `return fetch()...` – jfriend00 Apr 17 '18 at 04:00
  • Yes, of course I see your point now - was blinding myself. thanks! – Randy Casburn Apr 17 '18 at 04:02
  • In this way, I have to keep the return value on the top level of the test function, sometimes it's difficult such as using deounce wrapper. But when pass callback and wrap it to pTest, I can pass value by invoke cb (data) in any place in the test function. The solution is still good. Thanks mate. – JasonHsieh Apr 17 '18 at 10:33