创建Promise对象并要求以Promise对象方式返回返回其结果 在调用reject报Uncaught (in promise) 错误
示例
<button onclick="test()">test</button>
<script>
function promise() {
let promise = new Promise(function(resolve, reject) {
if(Math.random()>0.5?1:0){
reject(false);
}else {
resolve(true);
}
});
return promise;
}
function test() {
console.log(promise());
}
</script>
防止报错
<button onclick="test()">test</button>
<script>
function promise() {
let promise = new Promise(function(resolve, reject) {
if(Math.random()>0.5?1:0){
reject(false);
}else {
resolve(true);
}
});
promise.then((response)=>{
return response;
},(response)=>{
return response;
});
return promise;
}
function test() {
console.log(promise());
}
</script>