里面是伪代码:不能运行。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>05_为什么要用Promise</title>
</head>
<body>
</body>
<script>
/*
1.指定回调函数的方式更加灵活:
旧的:必须在启动异步任务前指定
promise: 启动异步任务 => 返回promise对象 => 给promise对象绑定回调函数
2.支持链式调用,可以解決回调地狱问题
什么是回调地狱? 回调函数嵌套调用,外部回调函数异步执行的结果是嵌套的回调函数执行的条件
回调地狱的缺点? 不便于阅读/不便于异常处理
解決方案? promise链式调用
终极解决方案?async/await
*/
/*1.1 使用纯回调函数*/
createAudioFileAsync(audioSettings, successCallback, failureCallback)
//重点:
//必须先指定回调函数,再启动异步任务
/*1.2 使用Promise*/
const promise = createAudioFileAsync(audioSettings);
setTimeout(() => {
promise.then(successCallback, failureCallback);
}, 7000)
//重点:
//promise相比较指定回调函数的方式更加灵活
/*
2.1,回调地狱
*/
doSomething(function (result) {
doSomethingElse(result, function (newResult) {
doThirdThing(newResult, function (finalResult) {
console.log('Got the final result: ' + finalResult)
}, failureCallback)
}, failureCallback)
}, failureCallback)
//多个串联的异步操作:也就是说第一个弄完后才弄第二个
/*
2.2.使用 promise的链式调用解决回调地狱
*/
dosomething()
.then(funetion(result) {
return doSomethingElse(result)
})
.then(function (newResult){
return doThirdThing(newResult)
})
.then(function (finalResult) {
console.log('Got the final result:' + finalResult)
})
.catch(failurecallback)//异常传递(中间任何一环出错,这里都会可以打印出来)
/*
2.3 async/await: 回调地狱的终极解决方案(相比较promise,async/await从编码上来看没有回调函数)
*/
async function request(){
try{
const result = await doSomething()//这一段代码必须成功后,才会执行下面的代码,以此类推
const newResult = await doSomethingElse(result)
const finalResult = await doThirdThing(newResult)
console.log('Got the final result' + finalResult)
}catch(error){
failureCallback(error)
}
}
</script>
</html>
回调函数配合promise使用,该代码可以运行:
<template>
<view>
</view>
</template>
<script>
import {
xyz
} from "../../common/index.js"
export default {
data() {
return {
}
},
onLoad() {
this.test()
},
mounted() {},
methods: {
test() {
xyz(function(msg) {
console.log(msg)
})
}
}
}
</script>
<style lang="scss">
</style>
function test1() {
return 1
}
function test2() {
return 2
}
function xyz(fun) {
new Promise((resolve, reject) => {
resolve(() => {
return 1
})
})
.then(
value => {
return test2();
}
)
.then(
value => {
if (value == 2) {
let obj = {
title: "你已经成功拿到数据了"
}
fun(obj)
}
}
)
}
export {
xyz
}