如果我的理解是正确的,你想在catch 块之后使用image1。
在这种情况下,我想,您将使用image1 调用某个函数。可以如下实现,部分sn-ps取自this answer:
const uploadToAWSBucket = (fileObject, callback) => { ... }; // described in the linked answer
uploadToAWSBucket(file, function callback(error, image1) {
if(error) { return next(error); }
someOtherFunction(image1, next); // "next" is passed as callback, with the assumption that nothing else needed to be called after that.
});
如果你想用someOtherFunction的结果再调用2个函数,可以这样做:
uploadToAWSBucket(file, function callback(error, image1) {
if(error) { return next(error); }
someOtherFunction(image1, function someOtherFunctionCb(error, someOtherFunctionResult) {
if(error) { return next(error); }
someOtherFunction2(someOtherFunctionResult, function someOtherFunction2Cb(error, someOtherFunction2Result) {
if(error) { return next(error); }
someOtherFunction3(someOtherFunction2Result, function someOtherFunction3Cb(error, someOtherFunction3Result) {
if(error) { return next(error); }
next(null, someOtherFunction3Result);
});
});
});
});
基本上,如果您使用回调,则不能有局部全局变量。我将尝试解释问题情况。
let image1 = null;
uploadToAWSBucket(file, function uploadToAWSBucketCallback(error, _image1) {
if(error) { return next(error); }
image1 = _image1;
});
someOtherFunction(image1, function someOtherFunctionCb(error, someOtherFunctionResult) {
if(error) { return next(error); }
...
});
在上面的sn-p中,someOtherFunction会在uploadToAWSBucketCallback被执行之前被调用。这意味着,image1 没有分配给_image1。现在,您知道当调用someOtherFunction 时image1 的值是多少。
第二个 sn-p 展示了如何通过将后续调用嵌套在回调中来将一个异步函数的结果传递给另一个。这使许多人的代码可读性降低。有像 async 这样的库,这有助于使事情变得更容易和可读。
第二个sn-p可以用async库的waterfall函数重写,如下所示:
async.waterfall([
function uploadToAWSBucketStep(callback) {
uploadToAWSBucket(file, callback);
},
function someOtherFunctionStep(image1, callback) {
someOtherFunction(image1, callback);
},
function someOtherFunction2Step(someOtherFunctionResult, callback) {
someOtherFunction2(someOtherFunctionResult, callback);
},
function someOtherFunction3Step(someOtherFunction2Result, callback) {
someOtherFunction3(someOtherFunction2Result, callback);
}
], function lastStep(error, someOtherFunction3Result) {
if(error) { return next(error); };
next(null, someOtherFunction3Result);
});