• 用Promise处理异步函数


    处理函数之间的异步问题,使其同步进行的其中一种方法,就是使用Promise。Promise在ES6中被提出。

    使用示例如下:

    假如有三个函数,要求按getone、gettwo、getthree的顺序执行。函数参数为Promise特有的resolve和reject,reslove和reject可在函数中返回结果。

     1 //异步方法一
     2  function getone(resolve,reject){
     3     setTimeout(function(){
     4         resolve("1");
     5     },3000)
     6 }
     7 //异步方法二
     8   function gettwo(resolve,reject){
     9       setTimeout(function(){
    10           resolve("2");
    11     },3000)
    12 }
    13 //异步方法三
    14  function getthree(resolve,reject){
    15      setTimeout(function(){
    16          resolve("3");
    17       },3000)
    18  }

    将getone函数作为参数生成Promise对象,用then来串联,result能拿到上一个函数返回的结果,then里面返回的是一个新的Promise对象,从而实现串联。

     1 var result = new Promise(getone)
     2 .then(function(resultone){
     3     console.log('----------one------------');
     4     console.log(resultone);
     5     return new Promise(gettwo);
     6 })
     7 .then(function(resulttwo){
     8     console.log('----------two------------');
     9     console.log(resulttwo);
    10     return new Promise(getthree);
    11 })
    12 .then(function(resultthree){
    13     console.log('-----------three---------');
    14     console.log(resultthree);
    15 })
    16 .catch(function(err){
    17     console.log(err);
    18 })

    结果如下:

     从而实现了这三个函数间的同步执行和前后传参。

  • 相关阅读:
    Golang rune类型
    使用Docker镜像部署ELK日志系统
    maven Setting详解
    JUC高并发编程的学习,知识点详细概括
    简单点,linux三种网络模式
    小巧的网页聊天工具提供GOFLY在线客服系统
    [Golang] 实现urlencode和urldecode编解码
    [Golang] gin模板渲染公用的头部和底部
    IM在线聊天软件多少钱?GOFLY在线客服系统
    [前端] 前端bootstrap colxs6 colmd3的布局意思
  • 原文地址:https://www.cnblogs.com/luoyihao/p/11592474.html
Copyright © 2020-2023  润新知