js异步调用转同步
js
// 执行两个嵌套的异步请求
function test() {
let promise_a = fetch('https://www.baidu.com/')
promise_a.then(res_a => {
res_a = "https://www.baidu.com/"
let promise_b = fetch(res_a)
promise_b.then(res_b => {
console.log("res_b = ", res_b)
}).catch(err => {
console.log("promise_b err=>", err);
})
}).catch(err => {
console.log("promise_a err=>", err);
})
}
test()
// *******************************************
// 将这两个嵌套的异步请求修改为同步的处理
function test_async() {
return new Promise(function(resolve, reject) {
let promise_a = fetch('https://www.baidu.com/')
promise_a.then(res_a => {
res_a = "https://www.baidu.com/"
let promise_b = fetch(res_a)
promise_b.then(res_b => {
resolve(res_b)
}).catch(err => {
// console.log("promise_b err=>", err);
reject(err)
})
}).catch(err => {
// console.log("promise_a err=>", err);
reject(err)
})
})
}
// 将异步请求用一个promise包裹 然后放到一个异步函数中
async function test() {
// console.log('test开始...');
var value1 = await test_async();
// console.log("value1 = ", value1);
return value1;
}
// 调用时使用await阻塞即可
let res = await test()
console.log("res = ", res)