ECMAScript-Promise/Async/Await

看完这个代码示例就明了了:

// Promise
const hoge = value => {
  return new Promise(resolve => {
        setTimeout(() => {
            resolve(value * 2);
        }, 1000);
    })
}

const fuga = value => {
  return new Promise(resolve => {
        setTimeout(() => {
            resolve(value * 3);
        }, 500);
    })
}

const promiseAllSample = () => {
    const promise1 = hoge(5);
    const promise2 = hoge(10);
    const promise3 = promise2.then(value => {
        return fuga(value);
    });

    return Promise.all([promise1, promise2, promise3]);
}

promiseAllSample().then(([a, b, c]) => {
    console.log(a, b, c); // => 10 20 60
});
// Async/Await
const hoge = value => {
  return new Promise(resolve => {
        setTimeout(() => {
            resolve(value * 2);
        }, 1000);
    })
}

const fuga = value => {
  return new Promise(resolve => {
        setTimeout(() => {
            resolve(value * 3);
        }, 500);
    })
}

const promiseAllSample = async () => {
    const [a, b] = await Promise.all([hoge(5), hoge(10)]);
    const c = await fuga(b);

    return [a, b, c];
}

promiseAllSample().then(([a, b, c]) => {
    console.log(a, b, c); // => 10 20 60
});

发布了110 篇原创文章 · 获赞 53 · 访问量 37万+

猜你喜欢

转载自blog.csdn.net/xianghongai/article/details/90551538