Async: 如何使用 async/await 使异步工作

创建于 2019-02-14  ·  10评论  ·  资料来源: caolan/async

var async = require('async');

var workPool = async.queue(async (task, taskComplete)=>{
  console.log(1, taskComplete);

  async.retry(3, async (retryComplete)=>{

    console.log(2, retryComplete);
    // retryComplete(null, task);

  });
});

workPool.push("test");

我想知道为什么我得到这个结果:

$ node test.js
1 undefined
2 undefined
question

最有用的评论

@pawelotto我认为你可以使用 node promisify util,我没有测试,但由于主回调函数签名是兼容的,我认为它会起作用。

所以上面的例子会变成(没有处理错误):

import async from "async"
import {promisify} from "util"

const promiseMapLimit = promisify(async.mapLimit)
const results = await promiseMapLimit(files, async file => { // <- no callback!
    const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
    const body = JSON.parse(text) // <- a parse error herre will be caught automatically
    if (!(await checkValidity(body))) {
        throw new Error(`${file} has invalid contents`) // <- this error will also be caught
    }
    return body // <- return a value!
})

所有10条评论

https://caolan.github.io/async/

在我们接受 Node 风格的回调函数的任何地方,Async 都接受异步函数。 但是,我们不会向它们传递回调,而是使用返回值并处理任何承诺拒绝或抛出的错误。

async.mapLimit(files, async file => { // <- no callback!
    const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
    const body = JSON.parse(text) // <- a parse error herre will be caught automatically
    if (!(await checkValidity(body))) {
        throw new Error(`${file} has invalid contents`) // <- this error will also be caught
    }
    return body // <- return a value!
}, (err, contents) => {
    if (err) throw err
    console.log(contents)
})

是的,异步不会将回调传递给async函数——只在任务完成时返回。

那么从最终回调函数返回值呢(而不是像这个例子中那样控制台记录它们)?

在大多数情况下,来自async函数的return值就可以工作。

哪个async函数正好返回一个值? 根据我的检查,它们返回无效,例如
直到

@pawelotto我认为你可以使用 node promisify util,我没有测试,但由于主回调函数签名是兼容的,我认为它会起作用。

所以上面的例子会变成(没有处理错误):

import async from "async"
import {promisify} from "util"

const promiseMapLimit = promisify(async.mapLimit)
const results = await promiseMapLimit(files, async file => { // <- no callback!
    const text = await util.promisify(fs.readFile)(dir + file, 'utf8')
    const body = JSON.parse(text) // <- a parse error herre will be caught automatically
    if (!(await checkValidity(body))) {
        throw new Error(`${file} has invalid contents`) // <- this error will also be caught
    }
    return body // <- return a value!
})

也许你可以试试新异步

@kazaff很酷,我不知道,谢谢!

@kazaff传奇!

@kazaff如何在 b4dnewz 的回答中使用新异步,只是无法返回结果

此页面是否有帮助?
0 / 5 - 0 等级