async在await循环中使用是否有任何问题?我正在尝试循环遍历文件数组和forEach每个文件的内容.
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
printFiles()
Run Code Online (Sandbox Code Playgroud)
这段代码确实有效,但这可能会出错吗?我有人告诉我你不应该使用await这样的高阶函数,所以我只是想问一下这是否有任何问题.
我想使用promises,但我有一个回调API,格式如下:
window.onload; // set to callback
...
window.onload = function() {
};
Run Code Online (Sandbox Code Playgroud)
function request(onChangeHandler) {
...
}
request(function() {
// change happened
...
});
Run Code Online (Sandbox Code Playgroud)
function getStuff(dat, callback) {
...
}
getStuff("dataParam", function(err, data) {
...
})
Run Code Online (Sandbox Code Playgroud)
API;
API.one(function(err, data) {
API.two(function(err, data2) {
API.three(function(err, data3) {
...
});
});
});
Run Code Online (Sandbox Code Playgroud)
我已经将我的代码重组为承诺,并构建了一个由多个回调组成的精彩长扁平承诺链.then().最后我想返回一些复合值,并且需要访问多个中间承诺结果.但是,序列中间的分辨率值不在最后一个回调的范围内,我该如何访问它们?
function getExample() {
return promiseA(…).then(function(resultA) {
// Some processing
return promiseB(…);
}).then(function(resultB) {
// More processing
return // How do I gain access to resultA here?
});
}
Run Code Online (Sandbox Code Playgroud) 我已经开发了几年的JavaScript,我根本不理解有关承诺的大惊小怪.
似乎我所做的只是改变:
api(function(result){
api2(function(result2){
api3(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
无论如何,我可以使用像async这样的库,例如:
api().then(function(result){
api2().then(function(result2){
api3().then(function(result3){
// do work
});
});
});
Run Code Online (Sandbox Code Playgroud)
哪个代码更多,可读性更低.我没有在这里获得任何东西,它也不会突然神奇地"平坦".更不用说必须将事物转换为承诺.
那么,这里的承诺有什么大惊小怪?
我已经阅读了几篇关于这个主题的文章,但我仍然不清楚是否Promise.reject与抛出错误之间存在差异.例如,
使用Promise.reject
return asyncIsPermitted()
.then(function(result) {
if (result === true) {
return true;
}
else {
return Promise.reject(new PermissionDenied());
}
});
Run Code Online (Sandbox Code Playgroud)
用投掷
return asyncIsPermitted()
.then(function(result) {
if (result === true) {
return true;
}
else {
throw new PermissionDenied();
}
});
Run Code Online (Sandbox Code Playgroud)
我的偏好是throw仅仅因为它更短而使用,但是想知道一个是否有任何优势.
请考虑以下以串行/顺序方式读取文件数组的代码.readFiles返回一个promise,只有在按顺序读取所有文件后才会解析.
var readFile = function(file) {
... // Returns a promise.
};
var readFiles = function(files) {
return new Promise((resolve, reject) =>
var readSequential = function(index) {
if (index >= files.length) {
resolve();
} else {
readFile(files[index]).then(function() {
readSequential(index + 1);
}).catch(reject);
}
};
readSequential(0); // Start!
});
};
Run Code Online (Sandbox Code Playgroud)
上面的代码可以工作,但我不喜欢按顺序进行递归递归.是否有一种更简单的方法可以重写此代码,以便我不必使用我的奇怪readSequential功能?
最初我试图使用Promise.all,但这导致所有readFile调用同时发生,这不是我想要的:
var readFiles = function(files) {
return Promise.all(files.map(function(file) {
return readFile(file);
}));
};
Run Code Online (Sandbox Code Playgroud) 如何拒绝async/await函数返回的promise?
例如,最初
foo(id: string): Promise<A> {
return new Promise((resolve, reject) => {
someAsyncPromise().then((value)=>resolve(200)).catch((err)=>reject(400))
});
}
Run Code Online (Sandbox Code Playgroud)
转换为async/await
async foo(id: string): Promise<A> {
try{
await someAsyncPromise();
return 200;
} catch(error) {//here goes if someAsyncPromise() rejected}
return 400; //this will result in a resolved promise.
});
}
Run Code Online (Sandbox Code Playgroud)
那么,在这种情况下,我怎么能正确地拒绝这个承诺呢?
javascript asynchronous typescript es6-promise ecmascript-2017
我正在尝试为博客平台创建一个构造函数,它内部有许多异步操作.这些包括从目录中获取帖子,解析它们,通过模板引擎发送它们等等.
所以我的问题是,让我的构造函数返回一个promise而不是它们调用的函数的对象是不明智的new.
例如:
var engine = new Engine({path: '/path/to/posts'}).then(function (eng) {
// allow user to interact with the newly created engine object inside 'then'
engine.showPostsOnOnePage();
});
Run Code Online (Sandbox Code Playgroud)
现在,用户可能还没有提供补充Promise链链接:
var engine = new Engine({path: '/path/to/posts'});
// ERROR
// engine will not be available as an Engine object here
Run Code Online (Sandbox Code Playgroud)
这可能会造成问题,因为用户可能会感到困惑,为什么 engine 在施工后无法使用.
在构造函数中使用Promise的原因是有道理的.我希望整个博客在构建阶段后正常运行.然而,在呼叫之后,它似乎几乎无法立即访问该对象new.
我一直在争论使用的东西,engine.start().then()或者engine.init()会返回Promise.但那些看起来也很臭.
编辑:这是在Node.js项目中.
javascript ×10
promise ×8
bluebird ×3
es6-promise ×3
node.js ×3
callback ×2
q ×2
angular-http ×1
angularjs ×1
architecture ×1
async-await ×1
asynchronous ×1
constructor ×1
scope ×1
sequential ×1
typescript ×1