前端的一个必学知识之一,Promise对象,是一种用来解决异步编程的方案
const promise = new Promise(function(resolve, reject) {
// ... some code
if (/* 异步操作成功 */){
resolve(value);
} else {
reject(error);
}
});
promise.then(function(value) {
// success
}, function(error) {
// failure
});//then的第二个参数为可选
举几个例子
function timeout(ms) {
return new Promise((resolve, reject) => {
//setTImeout的第三个参数,作为resolve函数的参数
setTimeout(resolve, ms, ‘done‘);
});
}
//调用函数,值100为setTImeout的时间,若异步状态为fulfilled则返回传递给resolve的值
timeout(100).then((value) => {
console.log(value);
});
let promise = new Promise(function(resolve, reject) {
console.log(‘Promise‘);
resolve();
});
promise.then(function() {
console.log(‘resolved.‘);
});
console.log(‘Hi!‘);
// Promise
// Hi!
// resolved
/*原因:
*promise在创建后便会立即执行,因此首先打印Promise
*then返回返回异步回调函数,所以执行放在后面,因此Hi提前到第二个执行
*/
getJSON("/posts.json").then(function(json) {
return json.post;
}).then(function(post) {
// ...
});
/*
*上面的代码使用then方法,依次指定了两个回调函数。
*第一个回调函数完成以后,会将返回结果作为参数,传入第二个回调函数。
*/
原文:https://www.cnblogs.com/kongbaifeiye/p/12609226.html