-2
我有2个回调其中一个。javascript node.js从回调分配变量到外部变量
service.call(data).then(result=>{
var err='';
service2.call(result.data, (result2,error)=>{
//I want to assign error to err
})
})
如何将内部变量赋值给外部变量?
我有2个回调其中一个。javascript node.js从回调分配变量到外部变量
service.call(data).then(result=>{
var err='';
service2.call(result.data, (result2,error)=>{
//I want to assign error to err
})
})
如何将内部变量赋值给外部变量?
您可以简单地在service2回调中使用err = error赋值。 另一个问题是,err变量只存在于第一个服务的回调中,所以目前还不清楚你将如何使用它。 无论如何,我已经草拟了几个模拟服务来表明这个任务是有效的。
// this is mock 'service'
const service = {
call: (data) => {
console.log('service is called with "' + data + '"');
// returning Promise because 'then' is used in consuming code
return new Promise((resolve, reject) => {
setTimeout(() => resolve({ data: '"This is result of call to service"' }), 1000);
})
}
}
// this is mock 'service2'
const service2 = {
// no Promise here because there is no 'then' in consuming code
call: (data, callback) => {
console.log('service2 is called with ' + data);
//setTimeout(() => callback('"This is result of call to service2 with ' + data + '"'), 1000); // this would be success scenario
setTimeout(() => callback(null, "service 2 failed"), 2000); // this is a failure scenario
}
}
// now call the services
service.call('data').then(result => {
console.log("service completed with " + JSON.stringify(result));
var err = '';
service2.call(result.data, (result2, error) => {
if (error) {
console.log('service2 failed with message "' + error + '"');
err = error;
}
})
// we're setting timeout big enough for service2 to complete to give it a chance to chang err variable before it's written to console
setTimeout(() => {
console.log('ultimate value of "err" variable is "' + err + '"');
},
5000 // you may try it with 1000 delay to see unchanged value
)
})
当函数做什么它应该@ibrahimmahrir回调被调用,那么我不认为这些回调的异步调用,因为它们是嵌套在回调中,链接有不同的故事 – wrangler
@avalon如果你这样做'err = error'在第二次回调中会按照它的设想工作,但如果在回调返回值之前使用err的其他地方,它将会是未定义的。因此,它取决于'err = error'后面的目的是什么? – wrangler
@wrangler根据nodejs哲学,它最可能是一个异步函数。 OP可能已经尝试自己分配值。 –