- 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?
 
    