将回调传递给异步函数甚至再次换行是否正常?

时间:2018-04-17 03:17:16

标签: javascript node.js asynchronous promise async-await

  • 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;
    

获取结果" json"我打算返回无法成为" test"的返回值。函数,因为该值仅在内部函数范围内可用,例如去抖动包装器。由于上述原因,我尝试传递回调函数并将回调包装为Promise函数(pTest),如下所示。

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;

这种方式对我有用,但我想知道它是否正确或有什么方法可以解决这种情况吗?

1 个答案:

答案 0 :(得分:1)

fetch API已经返回了一个承诺。将它包装在另一个Promise对象中实际上是一种反模式。它就像下面的代码一样简单:



/*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)
});