var fs = require('fs'); var readFile = function (fileName) { returnnewPromise(function (resolve, reject) { fs.readFile(fileName, function(error, data) { if (error) reject(error); resolve(data); }); }); }; var gen = function* () { var f1 = yieldreadFile('/etc/fstab'); var f2 = yieldreadFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); };
写成async函数,就是下面这样:
1 2 3 4 5 6
var asyncReadFile = asyncfunction () { var f1 = awaitreadFile('/etc/fstab'); var f2 = awaitreadFile('/etc/shells'); console.log(f1.toString()); console.log(f2.toString()); };
asyncfunctiongetTitle(url) { let response = awaitfetch(url); let html = await response.text(); return html.match(/<title>([\s\S]+)<\/title>/i)[1]; } getTitle('https://tc39.github.io/ecma262/').then(console.log) // "ECMAScript 2017 Language Specification"
//异步操作(即互不依赖),被写成继发关系。这样比较耗时,因为只有getFoo完成以后,才会执行getBar,完全可以让它们同时触发。 let foo = awaitgetFoo(); let bar = awaitgetBar(); // 写法一 let [foo, bar] = awaitPromise.all([getFoo(), getBar()]); // 写法二 let fooPromise = getFoo(); let barPromise = getBar(); let foo = await fooPromise; let bar = await barPromise;