4

Vue 中 Promise 的then方法异步使用及async/await 异步使用总结 - 香吧香

 1 year ago
source link: https://www.cnblogs.com/zjdxr-up/p/17045274.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

转载请注明出处:

1.Promise 的 then 方法使用  

  then 方法是 Promise 中 处理的是异步调用,异步调用是非阻塞式的,在调用的时候并不知道它什么时候结束,也就不会等到他返回一个有效数据之后再进行下一步处理;

  想了解 Promise 的使用,可以看这篇文章: ES6 中 Promise对象使用学习 

  使用示例:

new Promise(function (resolve, reject) {
  resolve(1);
}).then(console.log);
 
console.log(2);
// 2
// 1

  Promise 的回调函数属于异步任务,会在同步任务之后执行。上面代码会先输出2,再输出1。因为console.log(2)是同步任务,而then的回调函数属于异步任务,一定晚于同步任务执行。  

  但是,Promise 的回调函数不是正常的异步任务,而是微任务(microtask)。它们的区别在于,正常任务追加到下一轮事件循环,微任务追加到本轮事件循环。这意味着,微任务的执行时间一定早于正常任务。

setTimeout(function() {
  console.log(1);
}, 0);

new Promise(function (resolve, reject) {
  resolve(2);
}).then(console.log);

console.log(3);
// 3
// 2
// 1

  上面代码的输出结果是321。这说明then的回调函数的执行时间,早于setTimeout(fn, 0)。因为then是本轮事件循环执行,setTimeout(fn, 0)在下一轮事件循环开始时执行。

  所以在 使用Promise 的then方法时,一定要考虑 业务的处理逻辑,是否需要串行执行,如果需要串行执行,就要避免 后续的任务 早于 异步的任务执行结束

2. async await 使用

  使用 async 与 await 可以解决多个异步任务执行时的串行执行,也可以解决 Promise 使用 then 方法 异步执行的流程控制

  可以使用 async 和 await来得到我们的返回值

    • async关键词用于函数上(async函数的返回值是Promise实例对象)

    • await关键子用于async函数当中(await可以得到异步的结果)

  Promise构造函数的参数是一个函数,函数里面的代码是异步的,即Promise里面的操作,和Promise()外面的操作时异步"同时"进行的。此外,只要在函数前面加上async 关键字,也可以指明函数是异步的。

  async关键字实际是通过Promise实现,如果async 函数中有返回一个值 ,当调用该函数时,内部会调用Promise.solve() 方法把它转化成一个promise 对象作为返回,但如果timeout 函数内部抛出错误,那么就会调用Promise.reject() 返回一个promise 对象。若某函数调用一个异步函数(比如内部含有primise),该函数应用async修饰。

  await表示“等待”,修饰返回promise 对象的表达式。注意await 关键字只能放到async 函数里面。

//写一个async 函数,从而可以使用await 关键字, await 后面放置的就是返回promise对象的一个表达式    
        async getUserList(){
            const {data: res} = await this.$http.get('users', {
                params: this.queryInfo
            })
            //console.log(res)
            if (res.meta.status !== 200) return this.$message.error('获取用户列表失败! ')
            this.userlist = res.data.users
            this.total = res.data.total
        }

3. async/await处理多个异步请求

  • 第一个异步请求的结果

  • 可以作为第二个异步请求内部的参数,进行判断等数据操作。

  • 形成链式关系

function getSomething() {
    return "something";
}
  
async function testAsync() {
    return Promise.resolve("hello async");
}
  
async function test() {
    const v1 = await getSomething();
    const v2 = await testAsync();
    console.log(v1, v2);
}
  
test();

  执行的结果如图所示:

1110857-20230112003652313-1909223974.png

   这种写法可以保证的执行顺序;


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK