嵌套异步回调

  1. function double(value, success, failure) {
  2. setTimeout(() => {
  3. try {
  4. if (typeof value !== 'number') {
  5. throw 'Must provide number as first argument';
  6. }
  7. success(2 * value);
  8. } catch (e) {
  9. failure(e);
  10. }
  11. }, 1000);
  12. }
  13. const successCallback = (x) => {
  14. double(x, (y) => console.log(`Success: ${y}`));
  15. };
  16. const failureCallback = (e) => console.log(`Failure: ${e}`);
  17. double(3, successCallback, failureCallback);
  18. // Success: 12 (printed after roughly 1000ms)
  19. //NestingAsyncCallbacksExample01.js

异步返回值

  1. function double(value, callback) {
  2. setTimeout(() => callback(value * 2), 1000);
  3. }
  4. double(3, (x) => console.log(`I was given: ${x}`));
  5. // I was given: 6 (printed after roughly 1000ms)