Promise

Promise 对象是ES6新增的对象,她得作用是网络请求,是异步编程的一种解决方案。

1
2
3
4
5
6
7
8
9
10
11
12
13
let promise = new Promise((reslove, reject) => {
if (resolve) {
// resolve
} else {
// reject
}
});

promise.then((v) => {
// success
}, error => {
// error
})

案例(面试题):

怎么解决回调函数里面回调另一个函数,另一个函数的参数需要依赖这个回调函数。需要被解决的代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
$http.get(url).success((res) => {
if (success != res) {
success(res);
}
}).error((res) => {
if (error != undefined ) {
error(res)
}
})

success = (data) => {
if (data.id !=0 ) {
var url = "getdata/data?id=" + data.id + "";
$http.get(url).success(function (res) {
showData(res);
}).error(function (res) {
if (error != undefined) {
error(res);
}
});
}
}

请问下面代码一次输出什么?

1
2
3
4
5
6
7
8
9
10
11
12
13
setTimeout(function () {
console.log(1)
}, 0);
new Promise(function executor(resolve) {
console.log(2);
for (var i = 0; i < 10000; i++) {
i == 9999 && resolve();
}
console.log(3);
}).then(function () {
console.log(4);
});
console.log(5);

// 2、3、5、4、1
// 首先定时器会最后执行,Promise是一个异步对象,会先执行所以会输出 2、3 ,
// 然后,Promise 的 then 应当会放到当前 tick 的最后,但是还是在当前 tick 中,
// 因此,应当先输出 5,然后再输出 4 , 最后在到下一个 tick,就是 1 。

promise只有2个状态,成功和失败,怎么让一个函数无论成功还是失败都能被调用?

使用promise.all() // Promise.all方法的参数可以不是数组,但必须具有Iterator接口,且返回的每个成员都是Promise实例

Promise.all方法用于将多个 Promise 实例,包装成一个新的 Promise 实例。

分析下面这段代码,会输出什么内容::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 1000)
})
const promise2 = promise1.then(() => {
throw new Error('error!!!')
})

console.log('promise1', promise1)
console.log('promise2', promise2)

setTimeout(() => {
console.log('promise1', promise1)
console.log('promise2', promise2)
}, 2000)

运行结果:

1
2
3
4
5
6
7
8
9
promise1 Promise { <pending> }
promise2 Promise { <pending> }
(node:50928) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: error!!!
(node:50928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
promise1 Promise { 'success' }
promise2 Promise {
<rejected> Error: error!!!
at promise.then (...)
at <anonymous> }

原因:
promise 有 3 种状态:pending(进行中)、fulfilled(已完成,又称为Resolved) 或 rejected(已失败)。状态改变只能是 pending->fulfilled 或者 pending->rejected,状态一旦改变则不能再变。上面 promise2 并不是 promise1,而是返回的一个新的 Promise 实例。

0%