async await与promise
1.async 的返回值一定是一个promise。,即使你的函数里没有return.
1 2 3 4 5 6 7 | // 测试async的返回值 async function testAsync() { } let result = testAsync(); console.log(result); // 结果 Promise { undefined } |
2.因为有了await的限制,所以这里的async加不加都一样。
3.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // ----------- // 一个函数前如果加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-----') })
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步