Promise即是「承诺」之意,而产生的结果只有两种,不是「成功」就是「失败」,在程序里的表示方式是"resolve"(成功) or "reject"(失败),以下为基本语法:
let p = new Promise(function(resolve, reject) {
if (true) {
resolve('success'); // 成功
} else {
reject('failed'); // 失败
}
});
需要先new一个Project物件,物件中包含两个参数: resolve及reject。
resolve会在函式成功或为True的状况下执行,reject 则是在失败或为false的时候执行,resolve 和 reject 都有一个回传值,可将这个会传值透过.then传给下一个流程。
result = true;
let p = new Promise(function(resolve, reject) {
if (result) {
resolve('success');
} else {
reject("failed");
}
});
p.then((message) => {
console.log('This is the then ' + message)
}).catch((message) =>{
console.log('This is the catch ' + d)
// This is the then success
下面这段也可以这样排列,可读性较高:
p
.then((message) => {
console.log('This is the then ' + message)
})
.catch((message) =>{
console.log('This is the catch ' + d)
})
Project这个物件提供了两个方法(method): then()、catch(),如果想在Promise完成後执行後续的动作,我们可以这样定义 p.then()
、p.catch()
:
p.then
的意思是,当这个Promise里的程序执行完之後,且结果是resolve时,就会跳到then这里执行then里的程序。
p.catch
的意思是,当这个Promise里的程序执行完之後,且结果是reject时,就会跳到catch这里执行catch里的程序。
获取回传值
这些返回值会显现在回调函数里的参数,这样回调函数里的程序码就能使用这些返回值做进一步的处理。
参考资料:
https://www.oxxostudio.tw/articles/201706/javascript-promise-settimeout.html
Aloha!又是我少女人妻 Uerica!最近发现写铁人赛文章不但可以学习知识,还能训练自己如何当时...
1.原本的input 改为 el-autocomplete 并加上 :fetch-suggestio...
昨天和前天我们分别介绍了UITableView和XIB,今天我们就来利用这两个工具来实做一个能显示餐...
codepen 连结处: flex 精神时光屋3.双栏选单设计 练习六张图,三张一行 用css的 ...
用文本的方式打开文件,就可以看到版本了: FBXHeaderExtension: { FBXHead...