简体   繁体   中英

Not defined callback using async

I am trying to use async with the aim to make an sync flow.

Following the examples in this post , I did implement the code as follows:

function listBuckets(accessToken, prefix, callback) {
    var url = 'https://www.googleapis.com/storage/v1/b'
    request.get({
        url: url,
        auth: {
            'bearer': accessToken
        }
    }, function(err, res) {
        console.log('API Endpoint:  ' + url);
        console.log('Status Code: ' + res.statusCode);
        console.log('Response Body:\n' + res.body);
        callback(null, {
            statusCode: res.statusCode,
            body: res.body
        });
    });

}

router.get('/list', oauth2.required, (req, res, next) => {
    var operations = [];
    operations.push(listBuckets(req.user.accessToken, 'myPrefix', callback));
    async.series(operations, function (err, results) {
        const statusCode = results[0].statusCode;
        const body = results[0].body;
    });
});

However, I got the following error: ReferenceError: callback is not defined .

Could you help me in pointing out what I did wrong?

This line here:

operations.push(listBuckets(req.user.accessToken, 'myPrefix', callback));

What this does now, is it calls listBuckets with those parameters, then pushes that result to the operations array.

What you want to do is push a function to the array instead. If we look at the docs for the async lib, we'll notice that each of these functions accept a callback param, so we'll do that here: push a function which accepts callback , then calls the listBuckets function with that callback.

operations.push(callback => {
  listBuckets(req.user.accessToken, 'myPrefix', callback)
})

Feel free to comment on if and how my explanation can be improved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM