Home is it normal to pass callback into a async function and even wrap it again?
Reply: 0

is it normal to pass callback into a async function and even wrap it again?

user1379
1#
user1379 Published in April 26, 2018, 1:45 pm
  • 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?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.694738 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO