Mar*_*oon 1 node.js async-await ioredis
异步/等待方法:
Ids = ['abc','lmn','xyz']
Ids.forEach(function (resId){
console.log('inside loop');
async function operation(){
var curObj = await redisClient.get('key1');
console.log('done waiting');
}
}
Run Code Online (Sandbox Code Playgroud)
另一个函数的回调方法:
function operation(cb) {
redisClient.get('key1', cb);
}
operation(function(){
console.log('inside operation');
});
Run Code Online (Sandbox Code Playgroud)
我想等到 curObj 变量设置并按顺序执行代码以打印“完成等待”。我使用了 async/await 但它似乎没有按预期工作。然后我用相同的 get 方法使用回调仍然相同。我使用 ioredis 库。
我做错了什么?
异步/等待方法应该如下所示:
(async() => {
const Ids = ['abc','lmn','xyz'];
const operation = async (){
var curObj = await redisClient.get('key1');
console.log('done waiting');
}
for (const resId of Ids){
console.log('inside loop');
await operation();
}
})()
Run Code Online (Sandbox Code Playgroud)
没有asyncinforEach循环,但您可以将其与 一起使用for...of。
请注意,我使用 IIFE 函数只是为了示例如何在没有其他上下文的情况下使用 async/await。