Promise nested then execute order All In One
Promise nested then execute order All In One
Promise nested then
nested Promise
- 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
*/
- 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>: '✅'}
// ✅
refs
https://cdn.xgqfrms.xyz/promise/understanding-javascript-promises.pdf
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/13983194.html
未经授权禁止转载,违者必究!