xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Promise nested then execute order All In One

Promise nested then execute order All In One

Promise nested then

nested Promise

  1. not return new Promise

遇到 Promise 立即执行,Promise 后面紧跟着的第一个 then 也马上执行;
后面的 then 按照 Promise 创建的先后顺序,依次执行;


"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;


const promise = new Promise((resolve, reject) =>{
  log(1);
  resolve(1);
});

// then((json) => log(3, json), (err) => log(err));
promise
.then((v) => {
  // not new Promise ⚠️
  // return new Promise((ok, err) => {
  new Promise((ok, err) => {
    log(2);
    log(`v =`, v);
    // resolve callback, ok
    ok(`✅`);
    // reject callback, err
    err(`❌`)
  }).then((v) => {
    log(3);
    log(`v =`, v, `\n`);
    return v;
  }).then((v) => {
    log(4);
    log(`v =`, v, `\n`);
    return v;
  });
  // 遇到 Promise 立即执行,Promise 后面紧跟着的第一个 then 也马上执行,后面的 then 按照 Promise 创建的先后顺序,依次执行 then!
  return v;
})
.then((v) => {
  log(5);
  log(`v =`, v);
  return v;
})
.then((v) => {
  log(6);
  log(`v =`, v);
  return v;
});


/*

1
2
v = 1
3
v = ✅

5
v = 1
4
v = ✅

6
v = 1
*/


  1. return new Promise

"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;


const promise = new Promise((resolve, reject) =>{
  log(1);
  resolve(1);
});

// then((json) => log(3, json), (err) => log(err));
promise
.then((v) => {
  // return new Promise
  return new Promise((ok, err) => {
    log(2);
    log(`v =`, v);
    // resolve callback, ok
    ok(`✅`);
    // reject callback, err
    err(`❌`)
  }).then((v) => {
    log(3);
    log(`v =`, v);
    return v;
  }).then((v) => {
    log(4);
    log(`v =`, v);
    return v;
  });
  // return v;
})
.then((v) => {
  log(5);
  log(`v =`, v);
  return v;
})
.then((v) => {
  log(6);
  log(`v =`, v);
  return v;
});


/*

1
2
v = 1
3
v = ✅
4
v = ✅
5
v = ✅
6
v = ✅

*/

custom promise resolve / reject

const promise = new Promise((ok, err) => {
    log(`resolve vs ok`);
    // resolve callback, ok
    ok(`✅`);
    // reject callback, err
    err(`❌`)
  });
promise.then(v => console.log(v))
// resolve vs ok
// Promise {<fulfilled>: '✅'}
// ✅

image

refs

https://cdn.xgqfrms.xyz/promise/understanding-javascript-promises.pdf



©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2020-11-16 08:56  xgqfrms  阅读(81)  评论(2编辑  收藏  举报