是时候放弃回调了

直接上代码。
顺序调用三个方法,取得一个结果。

  1. 回调写法:
test1 = (data, success, error) => {
  success(data + "test1")
};
test2 = (data, success, error) => {
  success(data + "test2")
};
test3 = (data, success, error) => {
  success(data + "test3")
};

test1("test0", data => {
  test2(data, res2 => {
    test3(res2, res3 => {
        console.log(res3);
      }
    )
  })
})
  1. Promise写法
test1 = data => new Promise((resolve, reject) => resolve(data + "test1"));
test2 = data => new Promise((resolve, reject) => resolve(data + "test2"));
test3 = data => new Promise((resolve, reject) => resolve(data + "test3"));

test1("test0").then(data =>
  test2(data)
).then(data =>
  test3(data)
).then(data =>
  console.log(data)
)
  1. async和await写法
test1 = data => new Promise((resolve, reject) => resolve(data + "test1"));
test2 = data => new Promise((resolve, reject) => resolve(data + "test2"));
test3 = data => new Promise((resolve, reject) => resolve(data + "test3"));


test = async () => {
  let data = await test1("test0");
  data = await test2(data);
  data = await test3(data);
  console.log(data);
}
test()

你可能感兴趣的:(是时候放弃回调了)