• async await与promise


    1.async 的返回值一定是一个promise。,即使你的函数里没有return.

    // 测试async的返回值
    async function testAsync() {
    }
    let result = testAsync();
    console.log(result);
    
    // 结果 Promise { undefined }
    

      

    2.因为有了await的限制,所以这里的async加不加都一样。

     3.

    // -----------
    // 一个函数前如果加async和没有加sync的区别
    function testSometing() {
     console.log("进入testSometing");
     return "执行testSometingreturn";
    }
    async function testAsync() {
     console.log("进入testAsync");
     return Promise.resolve("hello async");
    }
    async function test() {
      console.log("进入test")
      let aa = await testSometing();
      console.log(aa)
      let a1 = await testAsync();
      console.log(a1)
      console.log("离开test")
    }
    test()
    var promise = new Promise((resolve)=> {
      console.log("进入promise");
      resolve("执行promise回调");
    });//关键点2
    promise.then((val)=> console.log(val));
    console.log("进程结束")
    

      

    例子3 

    var fs = require('fs');
    async function asyncPrint() {
      await new Promise(function (resolve,reject) {
        fs.readFile('await1_attach1.js','utf8',function(err,data){console.log('1----',data)
        if(err){
            reject(err);
        }else{
            resolve(data);
        }})
      })
      await new Promise(function (resolve,reject) {
        fs.readFile('await1_attach1.js','utf8',function(err,data){console.log('2----',data)
        if(err){
            reject(err);
        }else{
            resolve(data);
        }})
      })
    
      console.log('3----')
    }
    asyncPrint().then(() => {
      console.log('4-----')
    }).then(() => {
      console.log('5-----')
    })
    View Code

  • 相关阅读:
    HDU5090模拟,hash
    在Android手机上获取其它应用的包名及版本
    ubunut在系统恢复模式下无法改动rootpassword的分析和解决
    Index column size too large. The maximum column size is 767 bytes.
    java实现定时任务
    APP账号密码传输安全分析
    用RSA加密实现Web登录密码加密传输
    svn is already locked解决方案
    ajax跨域请求
    redis+spring配置
  • 原文地址:https://www.cnblogs.com/coding4/p/8685606.html
Copyright © 2020-2023  润新知